0

i would change the main query on a CPT archive page

the CPT is declare as "events", the name of the archive page I use is called 'archive-events.php" and this simple code won't work.

add_filter( 'pre_get_posts', 'pre_get_post_fct' );

function pre_get_post_fct( $wp_query ) {

    if( $wp_query->is_main_query() ) :

        echo "A";

    endif;

}

The thing is, I don't understand why it doesn't echo "A". I probably miss something....

Could you help me please ? Thanks !

3
  • where is this code located? It's unlikely that an A will be output in a place that's visible on the frontend without viewing source, and the filter your shared runs on all queries that are the main query. I suspect though that you've placed that filter inside archive-events.php which is far too late. Adding filters inside a theme template is a general anti-pattern and rarely works
    – Tom J Nowell
    Commented Sep 15, 2022 at 12:57
  • Thanks to reply, the code is located in "archive-events.php" just before <?php get_header(); ?>
    – nico
    Commented Sep 15, 2022 at 15:06
  • Writing it in function.php make it works. Of course. Sorry.
    – nico
    Commented Sep 15, 2022 at 15:08

1 Answer 1

1

pre_get_posts filters run before WordPress has figured out the main query, which is used to pick the template. For this reason you can't put it inside the template, it has to run before the template is picked, not afterwards.

For this reason, it has to go inside your themes function.php or in a plugin

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.