首頁  >  文章  >  CMS教程  >  快速提示:內容之後 - 同一類別的更多內容

快速提示:內容之後 - 同一類別的更多內容

王林
王林原創
2023-09-03 17:53:02946瀏覽

快速提示:内容之后 - 同一类别的更多内容

#您的部落格上有可靠的類別結構嗎?如果是這樣,您可能根本不需要「相關貼文」部分 - 您只需顯示相同類別的最新貼文即可。

在這篇文章中,我們將介紹「此類別的更多內容」部分,這是「相關貼文」(我們之前介紹過)的替代選項。


顯示你還有更多話要說

如果您將帖子按類別組織得很好,您可能會發現擁有帖子類別中的帖子列表很有用。

「相關貼文」並不總是答案:如果您的網站上的貼文按類別分隔,那麼「相關貼文」部分可能會「打破」這種分隔。

例如,如果您有一個關於不同職業群體的博客,則無法在有關資訊學的帖子下將有關紡織行業的新聞顯示為「相關新聞」。同一類別的許多最新帖子會更相關,對吧?

建立「此類別的更多內容」清單

正如您可能已經猜到的,列出貼文類別中的最新貼文比根據貼文標籤顯示相關貼文要容易得多。我們只需要獲取帖子的類別並列出該類別中的許多帖子,不包括訪客剛剛閱讀的帖子。我們可以在 get_posts() 函數中傳遞的參數包含我們需要的一切。

<?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="' . $permalink . '" 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;
}
?>

完成!您可以將此函數包含在您的functions.php 檔案中(或將其儲存為單獨的插件)並回顯它(如<?php echo wptuts_more_from_cat( 'More From This Category:' ); ? >) 在 single.php 檔案中的任何位置。


結論

是的,內容可能是“王”,但孤獨的王是軟弱的王,人們可能不會尊重那個“王”。

您認為還有更多的頁面元素可以幫助「王」嗎?請在下面發表您的評論 - 與我們分享您的想法對您來說始終很重要!

#

以上是快速提示:內容之後 - 同一類別的更多內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn