There are many situations a developer need to add more content to an article’s body. The most popular situations are adding social share icons and related posts. This post will introduce the hook way to add content to the body below.
The right way to carry out this task is to hook on the_content()
.
Table of Contents
Hook to every post including loop
function mytheme_add_social_icons_to_content( $content ) { $content .= '<div id="social_icons_wrapper">'; $content .= '<ul> <li><a href="javascript:void(0);" data-href="http://www.facebook.com/sharer.php?u={LINK}&t={TITLE}" class="Facebook"><span>Facebook</span></a></li> <li><a href="javascript:void(0);" data-href="https://twitter.com/share?url={LINK}&text={TITLE}" class="Twitter"><span>Twitter</span></a></li> <li><a href="javascript:void(0);" data-href="http://www.linkedin.com/cws/share?url={LINK}" class="LinkedIn"><span>LinkedIn</span></a></li> </ul>'; $content .= '</div>'; return $content; } add_filter( 'the_content', 'mytheme_add_social_icons_to_content' );
Hook to single post only
is_single()
is used to determine whether we need to add content to the post’s single template.
function mytheme_add_social_icons_to_content( $content ) { if( is_single() ) { $after_content = ''; $after_content .= '<div id="social_icons_wrapper">'; $after_content .= '<ul> <li><a href="javascript:void(0);" data-href="http://www.facebook.com/sharer.php?u={LINK}&t={TITLE}" class="Facebook"><span>Facebook</span></a></li> <li><a href="javascript:void(0);" data-href="https://twitter.com/share?url={LINK}&text={TITLE}" class="Twitter"><span>Twitter</span></a></li> <li><a href="javascript:void(0);" data-href="http://www.linkedin.com/cws/share?url={LINK}" class="LinkedIn"><span>LinkedIn</span></a></li> </ul>'; $after_content .= '</div>'; $content .= $after_content; } return $content; } add_filter( 'the_content', 'mytheme_add_social_icons_to_content' );