【问题标题】:How to filter comments in a post by a certain comment meta value如何通过某个评论元值过滤帖子中的评论
【发布时间】:2016-09-09 22:20:18
【问题描述】:

我正在尝试在 wordpress 帖子中创建 cmets 列表,以便它们仅列出具有特定 meta_keymeta_value 的 cmets。到目前为止,我已经尝试在 google 上找到答案,并且只发现了当有人在 cmets 表单中添加评论时如何分配元键/值。

在主题的functions.php

<?php

add_action( 'comment_post', function($comment_id) {
    add_comment_meta( $comment_id, $my_meta_key, $my_meta_value );
});

现在我想不通的是,如何让 wordpress 帖子过滤 cmets,以便它们只列出具有我希望它们的特定元键和值的 cmets。

我使用下划线创建了我的主题,并使用 wp_list_cmets() 函数在 cmets.php 中列出了 cmets。

【问题讨论】:

  • 您是否在主题中调用comments_template() 函数?
  • 是的,我也从 single.php 和 page.php 调用 cmets_template()。
  • 那么this 可能会有所帮助。
  • 对不起,但在我尝试阅读 url 之后,我仍然不知道如何过滤 cmets 以仅列出具有特定评论元键和值的那些。我可以要求进一步解释吗?
  • 您是否查看了我在那个答案中提到的示例链接?它包含一个基本用法。

标签: php wordpress function filtering


【解决方案1】:

下面是一个示例,如何通过comments_template_query_args 过滤器修改comments_template() 中的主评论查询(适用于WordPress 4.5+ 版本):

/**
 * Filter non-threaded comments by comment meta, in the (main) comments template
 */
add_filter( 'comments_template_query_args', function( $comment_args )
{
    // Only modify non-threaded comments
    if(    isset( $comment_args['hierarchical'] ) 
        && 'threaded' === $comment_args['hierarchical'] 
    )
        return $comment_args;

    // Our modifications
    $comment_args['meta_query'] = [
        [
            'key'     => 'some_key',
            'value'   => 'some_value',
            'compare' => '='
        ]
    ];        

    return $comment_args;
} );

您可以根据需要调整元查询。请注意,此示例假定 PHP 5.4+

【讨论】:

  • 我尝试使用上面的示例,但最终得到错误:解析错误:语法错误, 中的意外'$comment_args' (T_VARIABLE)....我正在使用 xamppp for windows使用 PHP 5.6.3 版,错误说明 $comment_args['meta_query'] = [ 所在的行。我想知道出了什么问题?编辑:我刚刚尝试修复代码格式,现在没有出现错误。我会在尝试代码后回来。
  • ps:这是未经测试的,我只是注意到缺少 ; (我更新了答案)。
  • 谢谢。我回过头来说,这正如我所愿。
  • 不客气,很高兴听到它对你有用@58YtQ2H83m17838963l61BU07Y8622
猜你喜欢
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多