简体   繁体   English

如何通过访问评论元数据的钩子更改 WordPress 评论输出?

[英]How to change WordPress Comment output via hooks accessing comment meta data?

I am looking to add some meta data to my Woo Commerce product reviews.我希望在我的 Woo Commerce 产品评论中添加一些元数据。

My plugin shows which product variant the customer is reviewing, and I wanted to add that information into each of the customer's reviews (comments), with a small thumbnail img of the product varient to fancy things up a bit as well.我的插件显示了客户正在评论的产品变体,我想将该信息添加到每个客户的评论(评论)中,并附上产品变体的小缩略图,以增加一些趣味性。

But I am having trouble finding a filter / hook to tap into.但是我很难找到可以利用的过滤器/挂钩。

I have tried this one...我试过这个...

add_filter( 'comment_text', function( string $comment_text ) {

    $comment_text = '<p>Comment text injection</p>' . $comment_text;

    return $comment_text;
});

It works, but the problem is , it does not provide much context... I need the comment ID so I can grab some meta data about the comment.它有效,但问题是,它没有提供太多上下文...我需要评论 ID,以便我可以获取有关评论的一些元数据。

The documentation says it is possible to for this filter to have a WP_Comment obj passed with the filter... but that doesn't happen in my case.文档说这个过滤器可以通过过滤器传递 WP_Comment obj ......但在我的情况下不会发生这种情况。

https://developer.wordpress.org/reference/hooks/comment_text https://developer.wordpress.org/reference/hooks/comment_text

Any suggestions on hooks/filters available to use - I don't really want to have to start hacking the comments template.关于可用的钩子/过滤器的任何建议 - 我真的不想开始破解评论模板。

The comment_text filter hook allow 3 function arguments (so you missed 2 of them): comment_text过滤器钩子允许 3 个函数参数(所以你错过了其中的 2 个):

  • $comment_text (string), the main filtered argument $comment_text (string),主要过滤参数
  • $comment (object), the current WP_Comment Object instance $comment (object),当前WP_Comment Object 实例
  • $args (array), an array of arguments $args (array),一个参数数组

So in this hooked function, here is an example targeting Order notes for example:所以在这个钩子函数中,这里有一个针对订单注释的例子:

add_filter( 'comment_text', 'customizing_comment_text', 20, 3 );
function customizing_comment_text( $comment_text, $comment, $args ) {
    if( $comment->comment_type === 'review' ) {
        $comment_text = '<p>Comment text injection</p>' . $comment_text;
    }
    return $comment_text;
}

Code goes in functions.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 functions.php 文件中。 Tested and work.测试和工作。

在此处输入图片说明


To get specific comment meta data you will use the functionget_comment_meta() like:要获取特定的评论元数据,您将使用get_comment_meta()函数,例如:

$meta_value = get_comment_meta( $comment->comment_ID, 'your_meta_key', true );

To Add specific comment meta data you will use the functionadd_comment_meta() like:要添加特定的评论元数据,您将使用函数add_comment_meta()如:

add_comment_meta( $comment_id, 'your_meta_key', $meta_value, $unique );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM