首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在帖子底部显示链接的文章(如相关文章)

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

WordPress Development用户
提问于 2021-08-04 15:18:03
回答 1查看 34关注 0票数 0

我发现了许多插件,用于在帖子之后显示相关帖子的列表。

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

YARPP --另一个相关的帖子插件就是这种插件的一个例子。

Is基于文章中已经存在的链接显示“相关”帖子的任何方式吗?

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

EN

回答 1

WordPress Development用户

发布于 2021-08-05 14:43:34

我处理这个问题的方法是创建一个名为related-posts.php的模板部分,或者类似的内容。在它中,我将遍历文章内容中的每个链接,并检查该url是否对应于另一个帖子(使用url_to_postid()函数)。然后,我会将所有非零id保存到一个数组中,最后,我将运行一个辅助wp循环来以您想要的方式显示这些帖子(即。缩略图+标题)就像这样:

(此代码部分是从这个答案修改的)

代码语言:javascript
复制
$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( '' . $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.
     */
}

我还没有测试这段代码,所以它可能有一些我没有预料到的错误。然而,它应该足以引导你朝着正确的方向前进。

票数 1
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/392895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档