在帖子底部显示链接文章(如相关帖子)

时间:2021-08-04 作者:collimarco

我找到了许多插件,可以在帖子之后显示相关帖子的列表。

然而,它们都基于分类法或文本内容。

YARPP–另一个相关帖子插件就是此类插件的一个例子。

Is there any way to display "related" posts based on the links already present in the article?

例如:一篇文章的主要内容中有link1和link2。是否可以在帖子底部再次显示link1和link2(就好像它们是“相关帖子”,带有文章标题和特色图片)?

1 个回复
SO网友:Nasif

我的方法是创建一个名为相关帖子的模板部分。php或类似的东西。在其中,我会浏览帖子内容中的每个链接,查看该url是否对应于另一篇帖子(使用url_to_postid() 函数)。然后,我会将所有非零id保存到一个数组中,最后,我会运行一个辅助wp循环,以您想要的方式显示这些帖子(即缩略图+标题)。类似这样:

(此代码部分修改自this answer)

$cont = get_the_content();
$related_post_ids = array();

//Only proceed if there is content
if ( !empty( $cont ) ) {
    // Get page content
    $html = new DomDocument;
    libxml_use_internal_errors(true); //See https://stackoverflow.com/questions/9149180/domdocumentloadhtml-error
    $html->loadHTML( \'<?xml encoding="UTF-8">\' . $cont );
    libxml_use_internal_errors(false);
    $html->preserveWhiteSpace = false;

    // Loop through all content links
    foreach( $html->getElementsByTagName( \'a\' ) as $link ) {

        // Get link href
        $link_url = $link->getAttribute( \'href\' );

        //If link href is not empty
        if( !empty( $link_url ) ){
            //Try to find the post that is being linked
            $linked_postid = url_to_postid( $link_url );

            //If we find the post, add it to the related_post_ids array
            if($linked_postid != 0){
                array_push($related_post_ids, $linked_postid);
            }
        }
    }
}

//If we found other posts linked in the content
if( count($related_post_ids) > 0 ){
    //Run a secondary loop to display the related posts
    $q_args = array( 
        \'post_type\' => \'any\',
        \'post_status\' => \'publish\'
        \'posts_per_page\' => 3 //Limit how many you show
        \'post__in\' => $related_post_ids, //Get only the posts we found
        \'orderby\' => \'post__in\' //Order them in the same order as the links appear in the post\'s content
    ); 

    $relposts_query = new WP_Query( $q_args ); 
    
    if ( $relposts_query->have_posts() ) : 
        // Start the Loop 
        while ( $relposts_query->have_posts() ) : $relposts_query->the_post(); 
            //Add your markup here, you may use the_post_thumbnail( ) for the featured image and the_title( ) for the article title
        endwhile; 
    endif; 
    
    wp_reset_postdata(); 
}else{
    /*
     * You may want to write some backup code here, what to display if the post in question
     * did not have any links to other posts.
     */
}
我还没有测试这段代码,所以它可能有一些我没有预料到的错误。然而,这应该足以引导你朝着正确的方向前进。

相关推荐

更改wp-admin/plugins.php上统计的插件数量

我已成功地使用从插件页面隐藏我的插件$wp_list_table 然而,顶部的分页仍然将插件列为“所有(3)”等。我成功地改变了$wp_list_table 的数组_pagination_args = total_items.但它仍然在页面顶部呈现插件-“全部(3)”。有什么办法可以解决这个问题吗?我找到了WP_Plugins_List_Table::prepare_items()具有全局$totals 变量,但我不确定我将如何改变这一点,在这个函数中$totals = array(); fore