• Resolved sant009m

    (@sant009m)


    Hi,

    I am using the below php code in Code snippets to allow random posts on the homepage.

    add_action('pre_get_posts','alter_query');
    function alter_query($query){
    if ($query->is_main_query() && is_home())
    $query->set('orderby', 'rand'); //Set the order to random
    }

    I want to allow random posts on the categories page too, since the above code works only on homepage. Can you help me with an updated code so that the category (Eg: https://xyz.com/category/cat1 ) also shows random posts.

    Thanks,

    Santosh M.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Theme Author ThemezHut

    (@pubudu-malalasekara)

    Hi,

    You can modify the code as shown below to display random posts on category archive pages as well.

    add_action('pre_get_posts','alter_query');
    function alter_query($query){
    if ($query->is_main_query() && (is_home() || is_category())) {
    $query->set('orderby', 'rand'); //Set the order to random
    }
    }

    Thank you.

    Thread Starter sant009m

    (@sant009m)

    Thank you very much

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Random posts on Category page’ is closed to new replies.