Wordpress - 通过post meta查询评论

时间:2017-07-25 21:52:15

标签: wordpress comments post-meta

我使用下面的代码(简化)来显示最近10条评论的列表:

<?php 

$args = array(
    'post_type'      => 'tarefa',
    'number'         => '10',
    'order'          => 'DESC',
    'orderby'        => 'comment_date',
    //'meta_key'        => 'field_name',
    //'meta_value'      => 'field_value',
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

foreach ( $comments as $comment ) {
    echo '<p>';
    echo get_the_title($comment->comment_post_ID) . '<br>'; //post title
    echo $comment->comment_content; // comment content
    echo '</p>';
};

?>

问题:

好吧, meta_key meta_value 似乎与 comment_meta 相关联......但在我的情况下,我必须根据 post_meta 键和值。

任何sugestions?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码。 您需要为帖子添加查询以使用元键获取post ide数组。 然后将该数组用于注释查询参数。

//QUERY FOR POSTS WITH META KEY AND VALUE (META QUERY)
$post_args = array(
    'post_type'  => 'post',
    'meta_key'     => 'meta key',//Meta key of post
    'meta_value'   => 'meta value',//String or Numeric value
    'meta_compare' => '=',
);
$post_query = new WP_Query( $post_args );
$posts_array= array();
if ( $post_query->have_posts() ) {
    while ( $post_query->have_posts() ) {
        $post_query->the_post();

        $posts_array[] = get_the_ID(); //Array of post ids

    }
    wp_reset_postdata();
}



//YOUR COMMENT ARGS SHOULD BE THIS
$args = array(
    'post_type'      => 'tarefa',
    'number'         => '10',
    'order'          => 'DESC',
    'orderby'        => 'comment_date',
    'post__in'        => $posts_array, //THIS IS THE ARRAY OF POST IDS WITH META QUERY
);

试试这个,然后让我知道结果。

答案 1 :(得分:0)

我在Stackoverflow的第一个问题是完美的。

非常感谢,Souvik!

在最终结果(简化)下面:

$post_args = array(
  'post_type'              => 'tarefa',
  'posts_per_page'         => -1,
  'meta_key'               => 'field_name',
  'meta_value'             => 'field_value',
);
$post_query = new WP_Query( $post_args );
$posts_array= array();
if ( $post_query->have_posts() ) {
    while ( $post_query->have_posts() ) {
        $post_query->the_post();
        $posts_array[] = get_the_ID(); //Array of post ids
    }
    wp_reset_postdata();
}

//YOUR COMMENT ARGS SHOULD BE THIS
$args = array(
    'number'         => '30',
    'order'          => 'DESC',
    'orderby'        => 'comment_date',
    'post__in'        => $posts_array, //THIS IS THE ARRAY OF POST IDS WITH META QUERY
);

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );

foreach ( $comments as $comment ) {
    echo '<p>';
    echo get_the_title($comment->comment_post_ID) . '<br>'; //post title
    echo $comment->comment_content; // comment content
    echo '</p>';
};