虽然实际问题与主题无关,但我会对代码进行一些修改,以使其更可靠、更快、更少的资源占用:
添加$content = \'\';
在函数顶部,这将消除通知:未定义变量通知
只能从中获取术语idwp_get_post_terms()
. 这将使此功能更快,并且您不会检索到您不打算使用的信息。只需添加array(\'fields\' => \'ids\' )
作为第三个参数
而不是使用$post
不太可靠的全局,请使用get_queried_object()
获取当前帖子信息
拆下计数器,我看没有必要这样做
WP_Query
只是个人喜好,因为您不需要设置postdata并使用$post
全球的这里是重写的函数
function pippin_related_posts($taxonomy = \'\') {
$current_post = get_queried_object();
$content = \'\';
if($taxonomy == \'\') { $taxonomy = \'post_tag\'; }
$tags = wp_get_post_terms($current_post->ID, $taxonomy, array(\'fields\' => \'ids\' ));
if ($tags) {
$first_tag = $tags[0];
$second_tag = $tags[1];
$third_tag = $tags[2];
$args = array(
\'post_type\' => $current_post->post_type,
\'posts_per_page\' => 4,
\'tax_query\' => array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => $taxonomy,
\'terms\' => $second_tag,
\'field\' => \'id\',
\'operator\' => \'IN\',
),
array(
\'taxonomy\' => $taxonomy,
\'terms\' => $first_tag,
\'field\' => \'id\',
\'operator\' => \'IN\',
),
array(
\'taxonomy\' => $taxonomy,
\'terms\' => $third_tag,
\'field\' => \'id\',
\'operator\' => \'IN\',
)
)
);
$related = new WP_Query($args);
if( $related->have_posts() ) {
while($related->have_posts() ) {
the_post();
$content .= \'<ul class="related-posts-box">\';
$content .= \'<li><a href="\' . get_permalink() . \'" title="\' . get_the_title() . \'">\' . get_the_title() . \'</a></li>\';
$content .= \'</ul>\';
}
wp_reset_postdata();
}
}
return $content;
}
add_action(\'the_content\', \'do_jt_related_posts\');
function do_jt_related_posts() {
if( is_singular(\'post\') ) :
echo get_the_content();
echo pippin_related_posts();
else :
echo get_the_content();
endif;
}