我更多地使用Ajax加载,并尝试通过标记获取相关帖子。工作原理:
$terms = wp_get_post_tags($post->ID); // get current categories
$term_array = []; // Create empty category array
foreach( $terms as $term ) { // Loop founf categories
$term_array[] = $term->slug;
}
echo do_shortcode(\'[ajax_load_more tag="\'. implode(",", $term_array) .\'" post__not_in="\' . $post->ID . \'" post_type="post" posts_per_page="3" scroll="false" progress_bar="true" progress_bar_color="blue" images_loaded="true" button_label="Load More" css_classes="related-posts-container" button_loading_label="Loading More" container_type="div" ]\');
但当我尝试实现一个功能,当标签为空时,我会按类别获取帖子,这让我崩溃。知道我做错了什么吗?function getRelatedPostsByTag(){
// Related Posts
$terms = wp_get_post_tags($post->ID); // get current categories
$term_array = []; // Create empty category array
foreach( $terms as $term ) { // Loop founf categories
$term_array[] = $term->slug;
}
$args = array(
\'posts_per_page\' => 1,
\'post__not_in\' => $post->ID,
\'tag\' => implode(",", $term_array),
\'post_type\' => \'post\'
);
$related_posts = get_posts( $args );
$query = \'tag="\'. implode(",", $term_array) .\'"\';
if (count($related_posts) > 1) {
return $query;
}
else {
wp_reset_postdata();
getRelatedPostsByCategory();
}
}
function getRelatedPostsByCategory(){
$categories = wp_get_post_categories($post->ID);
$categories_array = [];
foreach ($categories as $category) {
$categories_array[] = $category->CatSlug;
}
$query = \'category="\'. implode(",", $categories_array) .\'"\';
return $query;
}
wp_reset_postdata();
echo do_shortcode(\'[ajax_load_more \'. getRelatedPostsByTag() .\' post__not_in="\' . $post->ID . \'" post_type="post" posts_per_page="3" scroll="false" progress_bar="true" progress_bar_color="blue" images_loaded="true" button_label="Load More" css_classes="related-posts-container" button_loading_label="Loading More" container_type="div" ]\');