色射色,久久一级片,久久亚洲精品成人av无码网站,99热精品成人免费观看

WordPress代碼實現(xiàn)相關(guān)文章的幾種方法

2018-09-20 wordpress經(jīng)驗
  • 文章介紹
  • 快速入門
  • 評價&建議

WordPress有很多實現(xiàn)相關(guān)文章功能的插件,插件的優(yōu)點(diǎn)是配置簡單,但是可能會對網(wǎng)站的速度造成一些小的影響,所以很多人還是比較喜歡用代碼實現(xiàn)需要的功能,但是話又說回來了,代碼實現(xiàn)也有缺點(diǎn),就是配置復(fù)雜,不懂代碼的人完全摸不著頭腦或者只能照搬別人的代碼,還不如用插件。

這里我整理編寫了幾種用代碼實現(xiàn)相關(guān)文章的方法,這其中會詳細(xì)標(biāo)明各部分代碼的作用,以及如何自定義你想要的功能,希望對大家有所幫助,有什么問題可以給本文發(fā)表評論,我會及時給你回復(fù)。開始之前,說明一點(diǎn),以下所有方法輸出的HTML代碼格式都是以下形式,你可以根據(jù)需要進(jìn)行修改:

<ul id="xxx">
    <li>* <a title="文章標(biāo)題1" rel="bookmark" href="文章鏈接1">文章標(biāo)題1</a></li>
    <li>* <a title="文章標(biāo)題2" rel="bookmark" href="文章鏈接2">文章標(biāo)題2</a></li>
    ……
</ul>

方法一:標(biāo)簽相關(guān)

首先獲取文章的所有標(biāo)簽,接著獲取這些標(biāo)簽下的 n 篇文章,那么這 n 篇文章就是與該文章相關(guān)的文章了。現(xiàn)在可以見到的WordPress相關(guān)文章插件都是使用的這個方法。下面是實現(xiàn)的代碼:

<ul id="tags_related">
<?php
$post_tags = wp_get_post_tags($post->ID);
if ($post_tags) {
foreach ($post_tags as $tag)
{
    // 獲取標(biāo)簽列表
    $tag_list[] .= $tag->term_id;
}
// 隨機(jī)獲取標(biāo)簽列表中的一個標(biāo)簽
$post_tag = $tag_list[ mt_rand(0, count($tag_list) – 1) ];
// 該方法使用 query_posts() 函數(shù)來調(diào)用相關(guān)文章,以下是參數(shù)列表
$args = array(
        ‘tag__in’ => array($post_tag),
        ‘category__not_in’ => array(NULL),      // 不包括的分類ID
        ‘post__not_in’ => array($post->ID),
        ‘showposts’ => 6,               // 顯示相關(guān)文章數(shù)量
        ‘caller_get_posts’ => 1
    );
query_posts($args);
if (have_posts()) :
    while (have_posts()) : the_post(); update_post_caches($posts); ?>
<li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; else : ?>
    <li>* 暫無相關(guān)文章</li>
<?php endif; wp_reset_query(); } ?>
</ul>

使用說明:”不包括的分類ID” 指的是相關(guān)文章不顯示該分類下的文章,將同行的 NULL 改成文章分類的ID即可,多個ID就用半角逗號隔開。因為這里限制只顯示6篇相關(guān)文章,所以不管給 query_posts() 的參數(shù) tag__in 賦多少個值,都是只顯示一個標(biāo)簽下的 6 篇文章,除非第一個標(biāo)簽有1篇,第二個標(biāo)簽有2篇,第三個有3篇。。。。。。所以如果這篇文章有多個標(biāo)簽,那么我們采取的做法是隨機(jī)獲取一個標(biāo)簽的id,賦值給 tag__in 這個參數(shù),獲取該標(biāo)簽下的6篇文章。

方法二:分類相關(guān)

本方法是通過獲取該文章的分類id,然后獲取該分類下的文章,來達(dá)到獲取相關(guān)文章的目的。

<ul id="cat_related">
<?php
$cats = wp_get_post_categories($post->ID);
if ($cats) {
$cat = get_category( $cats[0] );
$first_cat = $cat->cat_ID;
$args = array(
        ‘category__in’ => array($first_cat),
        ‘post__not_in’ => array($post->ID),
        ‘showposts’ => 6,
        ‘caller_get_posts’ => 1);
query_posts($args);
if (have_posts()) :
while (have_posts()) : the_post(); update_post_caches($posts); ?>
<li>* <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute();
 ?>"><?php the_title(); ?></a></li>
<?php endwhile; else : ?>
<li>* 暫無相關(guān)文章</li>
<?php endif; wp_reset_query(); } ?>
</ul>

0 0

企業(yè)建站推薦正版商業(yè)主題,國內(nèi)專業(yè)團(tuán)隊開發(fā),完善售后,是您不二選擇。

正版主題商店

主題貓WP建站,累計幫助1300+客戶成功建站,為站長提供支持!

立刻開啟你的建站之旅
QQ在線客服

服務(wù)熱線

wordpress建站咨詢