我创建了一个相关的post函数,并将其添加到wordpress functions.php中。
function related_posts($args = array()) {
global $post;
// default args
$args = wp_parse_args($args, array(
'post_id' => !empty($post) ? $post->ID : '',
'taxonomy' => 'category',
'limit' => 4,
'post_type' => !empty($post) ? $post->post_type : 'post',
'orderby' => 'date',
'order' => 'DESC'
));
// check taxonomy
if (!taxonomy_exists($args['taxonomy'])) {
return;
}
// post taxonomies
$taxonomies = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids'));
if (empty($taxonomies)) {
return;
}
// query
// $related_posts = get_posts(array(
$related_posts = new WP_Query(array(
'post__not_in' => (array) $args['post_id'],
'post_type' => $args['post_type'],
'tax_query' => array(
array(
'taxonomy' => $args['taxonomy'],
'field' => 'term_id',
'terms' => $taxonomies
),
),
'posts_per_page' => $args['limit'],
'orderby' => $args['orderby'],
'order' => $args['order']
));
if $related_posts ) {
echo 'ok';
} else {
echo 'not ok';
}
?>
<?php if (!empty($related_posts)) { ?>
<h3 class="widget-title"><?php _e('<h5 class="title is-6">You Might Also Like</h5>', 'http://localhost/wordpress_john/wordpress1/'); ?></h3>
<div class="columns ">
<?php
include( locate_template('related-posts-template.php', false, false) );
?>
</div>
<?php
}
?>
<?php
wp_reset_postdata();
}
// related posts
add_action( 'comment_form_before', 'related_posts', 10, 0 ) ;
我已经创建了一个自定义帖子(post_type =>'custom')及其模板等,它们工作正常。但是,当查看者查看来自single-custom.php的自定义帖子时,此代码未显示相关帖子。 最初,此代码与get_posts一起使用,由于代码从get_posts返回空,所以我将其转换为WP_QUERY,为什么? Single.php的帖子按原样显示了相关帖子,但不显示single-custom.php。然后我将其转换为WP_QUERY,因为对get_posts进行了一些限制,然后对WP_QUERY进行了限制,但自定义帖子(single-custom.php)仍未显示任何相关的帖子,但是变量$ related_posts正在此处填充。救命!
答案 0 :(得分:0)
**Try this working code:**
<?php $customTaxonomyTerms = wp_get_object_terms( $post->ID, 'category', array('fields' => 'ids') );
$args = array(
'post_type' => 'events',
'post_status' => 'publish',
'posts_per_page' => 5,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $customTaxonomyTerms
)
),
'post__not_in' => array ($post->ID),
);
//the query
$relatedPosts = new WP_Query( $args );
//loop through query
if($relatedPosts->have_posts()){
echo '<ul>';
while($relatedPosts->have_posts()){
$relatedPosts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } echo '</ul>';
}else{
//no posts found
}
wp_reset_postdata();
?>