WordPress: How to Hook to After Content

There 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 body’s below.

The right way to carry our this task is to hook on the_content().

Hook to every post including loop

[php]
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}&amp;t={TITLE}" class="Facebook"><span>Facebook</span></a></li>
<li><a href="javascript:void(0);" data-href="https://twitter.com/share?url={LINK}&amp;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’ );
[/php]

Hook to single post only

is_single() is used to determine whether we need to add content to post’s single template.
[php]
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}&amp;t={TITLE}" class="Facebook"><span>Facebook</span></a></li>
<li><a href="javascript:void(0);" data-href="https://twitter.com/share?url={LINK}&amp;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’ );
[/php]

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close