在 WordPress 的文章頁面,一般我們都會推薦一些相關(guān)文章,對于WordPress 自帶的文章類型“post”,可以根據(jù)參考下面的文章來實現(xiàn):
WordPress添加相關(guān)文章功能(標題/縮略圖樣式)
WordPress相關(guān)文章插件:Yet Another Related Posts Plugin
WordPress相關(guān)文章插件:WordPress Related Posts
但如果是自定義文章類型(Custom Post type),要調(diào)用相關(guān)文章就需要修改查詢參數(shù)了。如果你還不知道什么是自定義文章類型,請查看:WordPress 自定義文章類型 介紹及實例解說
下面分享兩種情況下的調(diào)用方法,默認都是添加到主題的 single.php 或 single-custom_post_type.php 文件。
默認分類的相關(guān)文章
所謂“默認分類”是指自帶的文章類型post的分類“category”。也就是在注冊自定義文章類型時,你注冊的分類法就是 category 的時候。以下是代碼樣例:
<?php
/**
* WordPress 獲取自定義文章類型的相關(guān)文章(默認分類)
* http://www.ydqwiac.cn/related-custom-post-type-taxonomy.html
*/
// 獲取自定義文章類型的分類項目
$custom_taxterms = wp_get_object_terms( $post->ID,'category', array('fields' => 'ids') );
// 參數(shù)
$args = array(
'post_type' => 'YOUR_CUSTOM_POST_TYPE',// 文章類型
'post_status' => 'publish',
'posts_per_page' => 3, // 文章數(shù)量
'orderby' => 'rand', // 隨機排序
'tax_query' => array(
array(
'taxonomy' => 'category', // 分類法
'field' => 'id',
'terms' => $custom_taxterms
)
),
'post__not_in' => array ($post->ID), // 排除當前文章
);
$related_items = new WP_Query( $args );
// 查詢循環(huán)
if ($related_items->have_posts()) :
echo '<h3 class="related-posts-title">Related Posts</h3><ul>';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
endif;
// 重置文章數(shù)據(jù)
wp_reset_postdata();
?>
你需要根據(jù)自己的需要,修改參數(shù):
11行:’YOUR_CUSTOM_POST_TYPE’ 你需要修改為你的自定義文章類型
12行: 修改文章數(shù)量
還可以修改 26、29、32行的代碼來輸出自己想要的內(nèi)容,比如添加縮略圖,以及更多文章meta信息等。
自定義分類的相關(guān)文章
所謂“自定義分類”是指非默認的 category 這個分類法。以下是代碼樣例:
<?php
/**
* WordPress 獲取自定義文章類型的相關(guān)文章(自定義分類)
* http://www.ydqwiac.cn/related-custom-post-type-taxonomy.html
*/
// 獲取自定義文章類型的分類項目
$custom_taxterms = wp_get_object_terms( $post->ID,'your_taxonomy', array('fields' => 'ids') );
// 參數(shù)
$args = array(
'post_type' => 'YOUR_CUSTOM_POST_TYPE',// 文章類型
'post_status' => 'publish',
'posts_per_page' => 3, // 文章數(shù)量
'orderby' => 'rand', // 隨機排序
'tax_query' => array(
array(
'taxonomy' => 'your_taxonomy', // 分類法
'field' => 'id',
'terms' => $custom_taxterms
)
),
'post__not_in' => array ($post->ID), // 排除當前文章
);
$related_items = new WP_Query( $args );
// 查詢循環(huán)
if ($related_items->have_posts()) :
echo '<h3 class="related-posts-title">Related Posts</h3><ul>';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
endif;
// 重置文章數(shù)據(jù)
wp_reset_postdata();
?>
你需要根據(jù)自己的實際,修改如下參數(shù):
第 7 行和第 16 行:修改 your_taxonomy 為你的自定義分類法
11行:’YOUR_CUSTOM_POST_TYPE’ 你需要修改為你的自定義文章類型
12行: 修改文章數(shù)量
還可以修改 26、29、32行的代碼來輸出自己想要的內(nèi)容,比如添加縮略圖,以及更多文章meta信息等。
參考資料:
- http://isabelcastillo.com/related-custom-post-type-taxonomy
- http://isabelcastillo.com/get-related-posts-custom-taxonomy-category




