WordPress顯示相關文章

我想要在每篇文章的最下方顯示相關的文章(同分類),並且排除掉當前的文章

在程式碼片段新增function

將代碼複製、貼上

// 在文章下方顯示相關文章
function display_related_posts() {
    // 獲取當前文章的分類
    $categories = get_the_category();
    
    // 檢查是否有分類
    if ($categories) {
        $category_ids = array();
        
        // 獲取分類的 ID
        foreach ($categories as $category) {
            $category_ids[] = $category->term_id;
        }
        
        // 構建相關文章查詢參數
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => 8, // 設置顯示的相關文章數量
            'category__in' => $category_ids,
            'post__not_in' => array(get_the_ID()), // 排除當前文章
        );
        
        // 執行相關文章查詢
        $related_query = new WP_Query($args);
        
        // 檢查是否有相關文章
        if ($related_query->have_posts()) {
            echo '<div class="related-posts">';
            echo '<h3>相關文章</h3>';
            echo '<ul>';
            
            // 輸出相關文章的卡片
            while ($related_query->have_posts()) {
                $related_query->the_post();
                echo '<li>';
                echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
                echo '</li>';
            }
            
            echo '</ul>';
            echo '</div>';
            
            // 重置文章查詢
            wp_reset_postdata();
        }
    }
}


function display_related_posts_after_content($content) {
    if (is_single()) {
        ob_start(); 
        display_related_posts(); 
        $related_posts_content = ob_get_clean(); 

        
        $content .= '<div class="related-posts">' . $related_posts_content . '</div>';
    }

    return $content;
}
add_filter('the_content', 'display_related_posts_after_content');

完成後啟用

到每文章底下就會出現相同分類的文章標題

瀏覽次數:1