如何按类别显示相关帖子与当前帖子的下一篇文章(不是最新帖子或随机帖子)。我使用代码相关的帖子为二十世纪主题。但是现在,wentytwelve_entry_meta()中的作者是重复的。
请帮助我:
<div id="related_posts">
<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach((get_the_category()) as $category) {
$id = $category->cat_ID;
}
global $wpdb;
$query = "
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON
($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON
($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id = $category_ids[0]
AND $wpdb->posts.id < $post->ID
ORDER BY id DESC limit 3
";
$my_query = $wpdb->get_results($query);
if( $my_query) {
echo '<h3>Related Posts</h3><ul>';
foreach($my_query as $key => $post) {
?>
<li>
<div class="entry-header">
<div class="header-l">
<h1 class="entry-title">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
</h1>
<p class="datetime">
<?php twentytwelve_entry_meta(); ?>
</p>
</div>
<?php the_post_thumbnail(); ?>
</div>
<div class="entry-summary">
<?php
$str_content = wp_trim_words($post->post_content);
$str_content = str_replace('[', '<', $str_content);
$str_content = str_replace(']', '>', $str_content);
echo $str_content;
?>
</div>
</li>
<?php
}
echo '</ul>';
}
}?>
答案 0 :(得分:0)
WordPress习惯是使用WP_Query
类来从数据库中提取帖子,如果您可以修改代码以使用WP_Query
则会更容易。
当您使用自定义查询从数据库加载帖子时,the_permalink()
,the_title_attribute()
,the_title()
等模板标记将无法正常工作,这是主题函数{{ 1}}失败。
根据codex参考Displaying Posts Using a Custom Select Query
你应该尝试这样的事情:
twentytwelve_entry_meta()
其他有趣的帖子: