【问题标题】:WP - Extend main query with custom meta queryWP - 使用自定义元查询扩展主查询
【发布时间】:2019-06-21 07:06:32
【问题描述】:

我正在编写一个支持多个作者的帖子的主题。我将共同作者的 ID 保留在 post meta 中。问题是在作者存档页面上,我不仅需要显示作者的帖子,还需要显示他是合著者的帖子,并且它们需要在同一个循环中。 所以这是我的问题:有没有一种好方法可以用自定义查询扩展主查询(同时仍然保留分页等)。

add_action('pre_get_posts', function ($query) {
 if (is_admin() || !$query->is_main_query()) return;

 if ($query->is_archive() && $query->is_author()) {

 $author_id = get_query_var('author');

 // extend the main query with these post ids
 $coauthored_posts = get_posts([
 'fields'         => 'ids',
 'posts_per_page' => '-1',
 'post_status'    => 'publish',
 'meta_query' => [
        [
 'key' => 'co_authors',
 'value' => $author_id,
 'compare'   => 'LIKE',
        ]
      ]
    ]);
  }
});

【问题讨论】:

  • 您的查询结果是什么?您是否尝试在 meta_query 中使用 'IN' 运算符来进行“比较”?
  • 结果应该是这样 - 给我帖子的 ID 数组,作者被列为共同作者。问题是将这些帖子与主查询合并并进行分页。

标签: php wordpress


【解决方案1】:

你可以结合meta_query:

'meta_query' => array(
    'relation' => 'OR',
    array(
        'key' => 'author',
        'value' => $author_id,
        'compare'   => 'LIKE',
    ),
    array(
        'key'     => 'co_authors',
        'value'   => $co_author_id,
        'compare' => 'LIKE',
    ) 
)

【讨论】:

    【解决方案2】:
    add_action('pre_get_posts', function ($query) {
        if (is_admin() || !$query->is_main_query()) return;
        if ($query->is_archive() && $query->is_author()) {
    
            $author_id = get_query_var('author');
    
            // extend the main query with these post ids
            $cauthored_arg = array(
                'post_type' => 'post',
                'post_status'    => 'publish',
                'posts_per_page' => '-1',
                'orderby '=>'ID'
                'meta_query' => array(
                    array(
                        'key'     => 'co_authors',
                        'value'   => $author_id,
                        'compare' => 'LIKE',
                    ),
                )
            );  
    
            $coauthored_posts = new WP_Query( $cauthored_arg );
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2015-03-24
      • 2012-10-27
      相关资源
      最近更新 更多