0

So I tried two methods to simply display the main query posts in random order - simple. I'm also trying to understand all this better.

  1. Using the_content add_filter, with my own instance of WP_Query class.

  2. Using pre_get_posts add_filter.

I couldn't get the add_filter to randomize the posts. I also have to mention, Elementor plugin is used as page builder, so it's serving the blog page. Perhaps it's overriding my filter? Or I'm missing something.

Also, what would be the best method to do this, if my attempts below are not ideal?

My code with both methods as follows:

FIRST METHOD:

add_filter( 'the_content', 'thefunction',10 ,1 );
function thefunction($content) {

    $args = array(
       'post_type' => 'post',
       'orderby' => 'rand'
    );

    $mario_query = new  WP_Query( $args );

    if ( $mario_query->have_posts() ) {
        while ( $mario_query->have_posts() ) {
            $mario_query->the_post();
        }
    } else { echo 'error: no posts retrieved.'; }

    wp_reset_postdata();

    return $content;
}

SECOND METHOD:

add_filter( 'pre_get_posts', 'thefunction');
function thefunction($content) {

    if ( ! is_admin() && $query->is_main_query() ) {
        // Not a query for an admin page.
        // It's the main query for a front end page of your site.
 
            // Let's change the query using arguments.
            $query->set( 'orderby', 'rand' );

    }

    return $content;
}

4
  • The second method should work, just change this line: thefunction($content) { into thefunction($query) { and it should work fine.
    – admcfajn
    Feb 11, 2022 at 8:15
  • @admcfajn Thanks! It worked! Sometimes the little things get us :) You should post as a solution, so i can upvote you.
    – Mario
    Feb 11, 2022 at 9:10
  • 1
    Just to mention, I renamed all the instances of the $content variable to $query
    – Mario
    Feb 11, 2022 at 9:14
  • Nah, don't worry about it. If I answer you won't be able to delete the question. Thank you though :) glad it worked.
    – admcfajn
    Feb 11, 2022 at 9:44

1 Answer 1

0

Should be add_action not add_filter when using pre_get_posts

add_action( 'pre_get_posts', 'thefunction');
function thefunction($query) {

    if ( ! is_admin() && $query->is_main_query() ) {
        // Not a query for an admin page.
        // It's the main query for a front end page of your site.
 
            // Let's change the query using arguments.
            $query->set( 'orderby', 'rand' );

    }

    return $query;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.