本代码具有通用性。只要将代码嵌入到自定义文章详细页,将会显示出本文章同分类下的其它4篇文章。代码属于实际项目中的源代码,使用时请酌情修改使用。
<div class="about-shop">
<h3>相关文章</h3>
<?php
$post_type = $post->post_type;
$taxonomies = get_object_taxonomies($post_type, 'objects');
foreach($taxonomies as $taxonomy_slug => $taxonomy)
{
$terms = get_the_terms($post->ID, $taxonomy_slug);
if (!empty($terms))
{
$taxo = $taxonomy->name;
foreach($terms as $term)
{
$termslug = esc_html($term->slug);
$termlink = get_term_link($term);
}
}
}
$the_ID = get_the_ID();
$ID = array(
$the_ID
);
$args = array(
'post_type' => $post_type,
'tax_query' => array(
array(
'taxonomy' => $taxo,
'field' => 'slug',
'terms' => $termslug,
) ,
) ,
'post__not_in' => $ID,
'posts_per_page' => 4,
);
$query = new WP_Query($args);
if ($query->have_posts())
{
echo '<ul>';
while ($query->have_posts())
{
$query->the_post();
?>
<li>
<a href="<?php
echo get_permalink(); ?>">
<?php
$shopimg = get_post_meta($post->ID, '_shopimg', true);
if (!empty($shopimg))
{
echo $shopimg;
} ?>
<span>
<?php
echo get_the_title(); ?></span>
</a>
</li>
<?php
}
echo '</ul>';
wp_reset_postdata();
}
else
{
echo '<span style="padding:8px 15px 5px;display:block">No more items</span>';
}
?>
<div class="more_rela"><a href="<?php echo $termlink; ?>">更多相关文章</a></div>
</div>
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。