我的方法是创建一个名为相关帖子的模板部分。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.
*/
}
我还没有测试这段代码,所以它可能有一些我没有预料到的错误。然而,这应该足以引导你朝着正确的方向前进。