简体   繁体   English

如何在functions.php上使用多个pre_get_posts?

[英]How to use multiple pre_get_posts on functions.php?

I will try to explain as good as I can (sorry if my english is bad, this is not my native): 我将尽我所能解释(抱歉,如果我的英语不好,那不是我的母语):

I have two custom post types and two custom post type archive pages for each of them. 我有两个自定义帖子类型和两个自定义帖子类型存档页面。

To filter posts which are displayed in those pages I created two different functions inside functions.php file with "pre_get_posts" function as you can see in code below. 为了过滤显示在这些页面中的帖子,我在functions.php文件中使用“ pre_get_posts”函数创建了两个不同的函数,如下面的代码所示。

My functions.php: 我的functions.php:

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

some code here...

}

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

some code here...

}

The problem is that second function (my_pre_get_posts_2) is overwriting first one (my_pre_get_posts) and first function is not working on custom post type archive page. 问题在于第二个功能(my_pre_get_posts_2)覆盖了第一个功能(my_pre_get_posts),而第一个功能在自定义帖子类型存档页面上不起作用。

I tried to use is_post_type_archive( 'custom_post_type' ) but first function still is not working. 我尝试使用is_post_type_archive( 'custom_post_type' )但第一个功能仍无法正常工作。

What I need to do to assign first function only to specific custom post type archive page and not to call it on any other pages? 我该怎么做才能将第一个功能仅分配给特定的自定义帖子类型存档页面,而不在其他任何页面上调用它?

This is covered in the Codex . 食典中对此进行了说明 You should use a single callback: 您应该使用一个回调:

function my_pre_get_posts( $query ){
    if ( is_post_type_archive('cpt_1') ) {
        // Do stuff for a custom post type
    } elseif ( is_post_type_archive('cpt_2') ) {
        // Do stuff for a different custom post type
    }
}
add_action('pre_get_posts', 'my_pre_get_posts');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM