我为活动(戏剧表演)创建了一个自定义帖子类型。事件类别表示戏剧,事件是戏剧的表演。我希望用户对个人表演的评论(即活动自定义帖子类型的帖子)适用于该类别并出现在同一类别的所有其他活动中。问题是如何最好地实现这一目标。
一个(非常糟糕的)想法是使用 comment_post 挂钩并将评论的副本附加到同一类别的所有帖子。但首先,这不适用于该类别的新帖子(除非首次保存新帖子时复制评论),需要注意类别的更改,...并且重复评论似乎不太优雅这边走。
另一个想法是使用 comment_post 挂钩并将 comment_id 作为 termmeta 附加到类别,并开发不同的 comments.php 以从类别中获取评论。看起来有点复杂,但不可撤销。
有什么想法吗?
这样的事情能让你开始吗?
function get_show_comments() {
// Get the current post's categories.
$categories = get_the_category( get_the_id() );
// Get the category IDs.
foreach ( $categories as $category ) {
$category_ids[] = $category->cat_ID;
}
// Format for query.
$category_ids = implode(',', $category_ids);
// Get all posts with those categories.
$events = get_posts( 'cat=' . $category_ids );
// Put all their comments into an array.
foreach ( $events as $event ) {
$comments[] = get_comments( $event );
}
// Somewhere in here you'd presumably want to sort the comments by date, but I have to get to bed, lol.
return $comments;
}
我确信这可以优化一点,但希望这会有所帮助。
我根据 Shoelaced 的提案构建了我的解决方案。由于我对类别使用自定义分类法,因此有点不同:
function get_show_hello_comments() {
global $post_id;
// Get the current post's categories.
// Need to use get_the_terms since we use a custom taxonomy
$categories = get_the_terms($post_id, 'hello_event-category');
// Get the category IDs.
foreach ( $categories as $category ) {
$term_ids[] = $category->term_id;
}
// Get all posts with those categories.
$events = get_posts(
array(
'posts_per_page' => -1,
'post_type' => 'hello_event',
'tax_query' => array(
array(
'taxonomy' => 'hello_event-category',
'field' => 'term_id',
'terms' => $term_ids,
)
)
)
);
// Put all their comments into an array.
$comments = [];
foreach ( $events as $event ) {
$comments = array_merge($comments, get_comments( $event ));
}
// Sort ascending on dates
usort($comments, function($a, $b) {return strcmp($a->comment_date, $b->comment_date);});
return $comments;
}
我不想允许回复评论,这使得显示相当简单。在我的 OceanWP 子主题中,我包含了一个稍微修改过的 comments.php,它测试 post_type 是否是我的自定义帖子类型,在这种情况下:
$hello_comments = get_show_hello_comments($post->ID);
...
echo '<ol class="comment-list">';
$args= array('depth'=> 1,'max_depth' => 1);
foreach($hello_comments as $comment) {
oceanwp_comment($comment, $args, 1);
}
echo '</ol>'