我们知道Wordpress中的single.php
在循环内,所以我可以直接使用the_title()
或the_permalink()
,而无需创建自定义查询。
我已经这样做了,但在它的顶部,我有一个边栏,显示最新的帖子(自定义帖子类型)及其标题,链接和类别。
我可以检索所有相关的信息,除了类别链接。
我现在的代码返回类别uncategorized
为所有的帖子,即使他们都在一个特定的类别。
这是我使用的自定义查询,从自定义帖子类型cards
在single.php
中获取帖子
注意$categories = get_categories();
- foreach循环为所有帖子显示以下URL,这根本不是真的。
http://localhost/wonderhive/category/uncategorized/
如何修复并检索正确的类别URL?因为我已经检索了正确的类别名称。
<?php
$queryObject = new WP_Query( 'post_type=cards&posts_per_page=-1' );
if ($queryObject->have_posts()) {
while ($queryObject->have_posts()) {
$queryObject->the_post(); ?>
<div class="vista bg-black p-12 h-60 black">
<a href="<?php the_permalink(); ?>">
<img src="<?php the_post_thumbnail_url('small'); ?>" alt="gian" class="f-left foto r-100 ">
<div class="f-left">
<h5 class="gray2">
<?php
$thetitle = $post->post_title;
$getlength = strlen($thetitle);
$thelength = 45;
echo substr($thetitle, 0, $thelength);
if ($getlength > $thelength) echo "...";
?>
</h5>
</a>
<h6>
<?php
$categories = get_categories();
foreach ($categories as $cat) {
$category_link = get_category_link($cat->cat_ID);
echo $category_link;
}
?>
<a href="">
<?php $terms = wp_get_post_terms($post->ID,'categories');
foreach ($terms as $term) {
echo $term->name;
}
?>
</a>
</h6>
</div>
<span class="f-right"><?php echo get_the_date(); ?></span>
</div>
<?php }
}
?>
您应该使用$categories = get_the_category()
而不是$categories = get_categories()
。此函数将获取当前帖子的类别。
有关更多信息,请参阅get_the_category()的WordPress Codex。好运!