Further reading content should be based on the post category in order to get the title and permalinks of the related posts.
Table of Contents
First approach
We could use filter to change the post contents. But it does not work as expected.
The result is the new contents are added on each paginated page, and break the pagination link block.
function my_content_filter($content) {
$content .= further_reading();
return $content;
}
function stringInsert($str,$insertstr,$pos) {
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
add_filter( 'the_content', 'my_content_filter', 1 ); //set priority to 1 in order to add the new content right after post content from database.
Second approach
The alternative way is to modify paging plugin directly.
Plugin:
automatically-paginate-posts
File to change:
/wp-content/plugins/automatically-paginate-posts/automatically-paginate-posts.php
Inside paging plugin, it uses 'the_post
' filter to make pagination.
What we need to do is to change the post content directly in the $post object in filter_the_posts
function.
$the_post->post_content .= further_reading();
$content = $the_post->post_content;
Avoid plugin auto-update
In order to keep the custom changes we need to avoid the plugin update.
Change the plugin version number to a big number. Add 9 prefix in this case.
Version: 90.2
further_reading function
function further_reading(){
ob_start();
?>
<style>
.further-reading{margin-top:50px;}
.further-articles{background:#407a9e;width:100%;padding:8px 20px;color:white;font-size:18px;font-weight:bold;}
</style>
<div class="further-reading">
<div class="further-articles">相关文章</div>
<div style="margin:20px;">
<?php
//note that the_id() is not work in this context, so we have to identify the post from url.
$us = explode('/',$_SERVER['REQUEST_URI']);
$count= count($us);
$post_name = $us[$count-2];
if(is_numeric($post_name)) //paging number
$post_name = $us[$count-3];
$post = get_page_by_path( $post_name, OBJECT, 'post' );
$post_id = $post->ID;
$cats = get_the_category($post_id);
foreach($cats as $cat){
$related_posts = get_posts( array('posts_per_page' => 5,'category'=> $cat->cat_ID ) );
foreach($related_posts as $p){
setup_postdata( $p );
if($p->ID == $post_id) continue;
echo '<a href="'.get_permalink( $p->ID ).'">'.get_the_title( $p->ID ).'</a><br>';
}
}
?>
</div>
<div style="clear: all;"></div>
</div>
<?php
$text = ob_get_contents();
ob_end_clean();
return $text;
}
Comments
Welll composed artcles like yours renews myy faityh in today’s writers.You’ve writtten information I can finally agree on and also use.Many thanks for sharing.