飞龙博客

feilong.org

query related posts by the category or categories

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

<?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

新作:

旧文:

AI表情 AI音乐 blog money bui 教程 echarts 教程 eclipse 教程 html css 教程 IT趋势 js 教程 json 教程 mysql 教程 nodejs npm 教程 onblog SQLite 教程 tutorials vscode 教程 wap网站 winpe启动盘 wordpress 主机推荐 人工智能 前端开发 博客 名企名网 域名注册 常用软件 建站程序 操作系统 教程 数码 无线上网 日记 电子商务 电脑笔记本 网站 网站优化 网站开发 网站推广 网站策划 网络 虚拟现实 默认