wordpress - Can you use pre_get_posts outside of the main query? -
i'm new wordpress , have been learning lot pre_get_posts lately. understand basic concept getting tripped on part of documentation.
from codex:
"similarly, pre_get_posts not work if used in template files (e.g., archive.php), since called after query has been completed."
if can't use in template files, mean it's on index.php? if that's case, why there example further down page pre_get_posts used change how archive displays?
i understand power of pre_get_posts (over query_posts especially) i'm having hard time finding how can used many times on 1 site. see shows being used once , main loop.
any guidance appreciated.
files archive.php
, category.php
wordpress calls template files. documentation says, page templates have high level of specificity. explain why query initialized before template files being called , therefore, pre_get_posts
miss it's point on template files.
you able show archive without template files archive.php
, category.php
, pre_get_posts
- indeed - meant called on main query. means that, if add add_action('pre_get_posts', 'my_callback_function')
functions.php
file, alter query site-wide. can filter on specific page types inside callback so:
function my_callback_function($query){ // if page type category if(is_category()){ $query->set('posts_per_page', 7); } // except search page types if(!is_search()){ $query->set('posts_per_page', 4); } }
this way there's no need call pre_get_posts
twice.
if want perform multiple queries or specify archive.php
query, use instances of wp_query()
.
Comments
Post a Comment