不使用插件让WordPress按分类自动调用相关文章

wordpress 在WordPress文章后面列出相关文章,可以方便读者浏览更多相关的内容,通过下面的代码即可实现自动显示相关文章(按分类)。 首先,将下面的代码粘贴到你的主题functions.php文件中: // "More from This Category" list by Barış Ünver @ Wp...
不使用插件让Wordpress按分类自动调用相关文章
wordpress

WordPress文章后面列出相关文章,可以方便读者浏览更多相关的内容,通过下面的代码即可实现自动显示相关文章(按分类)。

首先,将下面的代码粘贴到你的主题functions.php文件中:

// "More from This Category" list by Barış Ünver @ Wptuts+  
function wptuts_more_from_cat( $title = "More From This Category:" ) {  
    global $post;  
    // We should get the first category of the post  
    $categories = get_the_category( $post->ID );  
    $first_cat = $categories[0]->cat_ID;  
    // Let's start the $output by displaying the title and opening the <ul>  
    $output = '<div id="more-from-cat"><h3>' . $title . '</h3>';  
    // The arguments of the post list!  
    $args = array(  
        // It should be in the first category of our post:  
        'category__in' => array( $first_cat ),  
        // Our post should NOT be in the list:  
        'post__not_in' => array( $post->ID ),  
        // ...And it should fetch 5 posts - you can change this number if you like:  
        'posts_per_page' => 5  
    );  
    // The get_posts() function  
    $posts = get_posts( $args );  
    if( $posts ) {  
        $output .= '<ul>';  
        // Let's start the loop!  
        foreach( $posts as $post ) {  
            setup_postdata( $post );  
            $post_title = get_the_title();  
            $permalink = get_permalink();  
            $output .= '<li><a href="'%20.%20$permalink%20.%20'" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';  
        }  
        $output .= '</ul>';  
    } else {  
        // If there are no posts, we should return something, too!  
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';  
    }  
    // Let's close the <div> and return the $output:  
    $output .= '</div>';  
    return $output;  
}  

之后,打开single.php文件,在适当位置添加调用函数:

<?php echo wptuts_more_from_cat( 'More From This Category:' ); ?>  

给TA打赏
共{{data.count}}人
人已打赏
wordpress教程

实用的WordPress网站加速,WP网站加速方法

2023-2-16 23:45:08

wordpress教程

从零开始制作WordPress主题,了解文件构成

2023-2-16 23:45:09

【腾讯云】11.11云上盛惠!云服务器首年1.8折起,买1年送3个月!
11.11云上盛惠!海量产品·轻松上云!云服务器首年1.8折起,买1年送3个月!超值优惠,性能稳定,让您的云端之旅更加畅享。
查看更多相关信息>>
站长

(工作日 10:00 - 22:30 为您服务)

2026-05-13 02:25:31

您好,无论是售前、售后、意见建议……均可通过联系工单与我们取得联系。

猜你想问:

  • 购买的模板免费包安装吗?

  • 这个演示地址有吗?

  • 购买vip会员可以下载哪些模板?

您的留言我们已经收到,我们将会尽快跟您联系!
取消
立即选择任一渠道联系我们