【问题标题】:Custom filter for WordPress loop with multiple post types具有多种帖子类型的 WordPress 循环的自定义过滤器
【发布时间】:2018-04-25 11:13:26
【问题描述】:

我正在构建一个 WordPress 网站,我想在其中显示一些页面以及博客索引中的帖子。棘手的条件是,WP_Query 应该返回所有“帖子”,但是当涉及“页面”时,它应该只获取具有特定父 ID 的页面,例如父 ID 为 1、2、3 等。

我想知道是否有可能在一个 WP_Query 中完成此操作,同时保留 WordPress 循环和函数,如 have_posts(),分页函数,如 previous_posts_link() 等。这可能吗?有人能指出我正确的方向吗?请让我知道是否需要我提供更多信息或是否有任何不清楚的地方。

谢谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    使用插件进行更多研究找到了解决方案 - wp-combine-queries

    示例代码如下

    //------------------------
    // Children pages query #1
    //------------------------
    $pages = [
        'post_type'      => 'page',
        'post_parent__in' => [
            1944,1962,1343,1377,909,952 // Post id's of parents
         ],
        'posts_per_page' => -1
    ];
    
    //-------------------
    // All Posts Query #2
    //-------------------
    $posts = [
       'post_type'      => 'post',
       'posts_per_page' => -1
    ];
    
    //---------------------------
    // Combined queries #1 + #2:
    //---------------------------
    $args = [
        'paged'               => get_query_var( 'paged', 1 ),
        'combined_query' => [        
            'args'   => [ $pages, $posts ],
            'union'  => 'UNION',
        ]
    ];
    
    //---------
    // Output:
    //---------
    $posts_to_display = new WP_Query( $args );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多