6

I am currently hooking on the_content() but that goes through the Wordpress loop too. How can I only hook on the Single.php page?

Also, is there a way to only look on the first X posts in the Wordpress loop?

By the way, I am creating a plugin

4
  • You want to add extra stuff to the end of the_content, but you only want it to happen when on single.php?
    – Pippin
    Jun 28, 2012 at 22:45
  • Yes. Also, I wanted to add something at the bottom of the content for the X most recent posts.
    – Strawberry
    Jun 28, 2012 at 22:50
  • You should probably expand your question a little more, because right now it doesn't make much sense. If you want to modify single.php, open up single.php and modify it. By its nature, single.php will only have a single post in the loop. To get other posts, you'll need a secondary loop after your main loop.
    – SickHippie
    Jun 28, 2012 at 22:52
  • I am creating a plugin.
    – Strawberry
    Jun 28, 2012 at 22:55

2 Answers 2

20

This will handle appending the content to single posts:

function yourprefix_add_to_content( $content ) {    
    if( is_single() ) {
        $content .= 'Your new content here';
    }
    return $content;
}
add_filter( 'the_content', 'yourprefix_add_to_content' );
9

Just to add to Pippin's answer, in my case some content were also being shown in other parts of the single page, e.g. sidebar. Checking just is_single() also triggered the content modification in the other areas. Here's another check so that only the main content will have appended stuff:

function yourprefix_add_to_content( $content ) {

    if( is_single() && ! empty( $GLOBALS['post'] ) ) {

        if ( $GLOBALS['post']->ID == get_the_ID() ) {

            $content .= 'Your new content here';

        }

    }

    return $content;
}
add_filter('the_content', 'yourprefix_add_to_content');
1
  • This is the more accurate answer to this question.
    – Christine Cooper
    Sep 29, 2017 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.