飞龙博客

妙法莲华经

query related posts by the category or categories

feilong.org 修订于2010-06-06 02:13:51 240 次浏览

<?php $postcats = get_the_category();

if($postcats){
foreach ($postcats as $cat) {
$catslug = $cat->slug;//get one of category slugs each by php foreach
$cslug = str_replace("tips-", "", $catslug);
$slug = str_replace("scenery-", "", $cslug);
$slu = str_replace("hotels-", "", $slug);//get the cleanest slug by str_replace()
$sslu = 'scenery-'.$slu;
$catids[count($catids)] = get_term_by( 'slug', $sslu, 'category' )->term_id;//get id by slug and fetch the value for the array
}}

print_r($catids);//show the array content by print_r()
$cats = implode(',', $catids);//change or turn the array into a string by implode()
unset($catids);//when you are on achieve.php,you should eliminate the effects of the array by the unset().unset() must be put after implode()
echo $cats;//show the imploded string of cats by echo ?>

<?php $args = 'cat='.$cats.'&showposts=5';//feilong fond the best way to get the $args for query_posts() if there are multiple categories for the post
query_posts($args); ?>

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<a href="<?php the_permalink() ?>"><img src="<?php echo url_of_first_image() //url_of first_image() is a function in functions.php to get the first image through img tag in a post ?>"/></a>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php else : ?>
<?php endif; //can be miss out sometime along with if(have_posts() ?>
<?php wp_reset_query(); //must use this tag if you use query_posts() to list post in a category or in categories outsite of the main wordpress loop ?>
<!-- /feilong.org test area end.Best luck to you my friends who read the post -->

<!--another way to get related posts in category or categories -->
<!--more common but a bit more difficult than above -->
<!--feilong gets related posts in single.not suitable for achieve -->
<!-- post by feilong on 20100606 url is http://feilong.org/query-posts-in-category-or-categores-->

<!--end of feilong test -->

a plugin http://playground.ebiene.de/400/related-posts-by-category-the-wordpress-plugin-for-similar-posts

更新网址:https://feilong.org/query-related-posts-by-the-category-or-categories
最初发布:20100606 02:13:51 feilong.org 于广州

加入收藏夹,查看更方便。

所在分类: wordpress

新作:

旧文: