【问题标题】:WordPress Failing to add custom post type to query using pre_get_postsWordPress 无法使用 pre_get_posts 添加自定义帖子类型进行查询
【发布时间】:2017-06-27 22:01:20
【问题描述】:

我未能使用 pre_get_posts 将自定义帖子类型添加到查询中。我创建了自己的主题并集成了这个插件 (https://github.com/Develop-With-WP/wp-job-listing)。

我现在如何将这个新的 post_type 'job' 添加到我的查询中?我试过这个:

function add_my_post_types_to_query( $query ) {
    if ( is_home() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'page', 'movie', 'job' ) );
    return $query;
}
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

我可以检查 post_type 但是当我将 [shortcode_debug] 放在编辑的帖子中并调用 /general/first-blog/ 时。

但是当我调用 /job/sales/ 时,它仍然没有呈现任何内容。我错过了什么?

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    试试这个,

    function add_my_post_types_to_query( $query ) {
        if ( $query->is_home() && $query->is_main_query() )
            $query->query_vars[ 'post_type' ] = [ 'post', 'page', 'movie', 'job' ];    
    }
    add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
    

    【讨论】:

    • 还是没有结果。我把它放在了 github.com/Develop-With-WP/wp-job-listing 的 wp-job-cpt.php 中。这是正确的做法吗?
    • 我认为如果放在那个文件中它应该可以工作。但请尝试将其放入主题的 functions.php 中以进行测试
    • 还是不行。奇怪的是,我什至无法将任何内容(例如 $post_type = 'Test'; echo $post_type;)回显到 /job/sales/ 。另外,如果我在编辑器中放一些东西,它就不存在了。对于 /general/first-blog/ 它就在那里 ...
    • 我有一个类似的 sn-p,就像我的回答中的那个一样,在客户的实时站点上工作得很好。我认为它应该可以工作,除非您的代码中的其他地方有错误。
    • 现在可以了。问题还在于函数 cfs_load_templates() 在返回 get_page_template() 时导致错误;我拿了 get_page_template();出来了,现在它的工作..
    【解决方案2】:
    add_action( 'pre_get_posts', 'get_posts_plus_cpt' );
    function get_posts_plus_cpt( $query ) {
       if ( $query->is_home() && $query->is_main_query() ) {        
          $query->set( 'post_type', 'job' );
       }
    }
    

    【讨论】:

    • 谢谢,但很遗憾,没有结果。如下所述......奇怪的是我什至无法将任何内容(如 $post_type = 'Test'; echo $post_type;)回显到 /job/sales/ 。另外,如果我在编辑器中放一些东西,它就不存在了。对于 /general/first-blog/ 它就在那里 ...
    【解决方案3】:
    add_action( 'pre_get_posts', 'get_posts_plus_cpt' );
    
    function get_posts_plus_cpt( $query ) {
    
        if ( $query->is_home() && $query->is_main_query() ) {        
           $query->set( 'post_type', 'job' );
        }
        return $query;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多