Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

How to display featured image after first paragraph

  • I dont know if there is a newer solution for displaying featured image after first paragraph.

    I was using the hook from David here

    It was working at front but I was getting error undefined $post variable and null property error for the $post->ID. in error_log file.

    So, I used global $post; and changed function like following:

    add_filter( 'the_content', 'insert_featured_image', 20 );
    function insert_featured_image( $content ) {
        if ( ! is_single() || is_admin() ) {
            return $content;
        }
    
        global $post;
    
        // Safety check in case $post is null or not an object
        if ( ! isset( $post ) || ! is_object( $post ) ) {
            return $content;
        }
    
        // Check if post actually has a featured image
        if ( ! has_post_thumbnail( $post->ID ) ) {
            return $content;
        }
    
        $feat_img = get_the_post_thumbnail( $post->ID, 'post-single' );
    
        return prefix_insert_after_paragraph(
            '<div class="incontent-featured-image">' . $feat_img . '</div>',
            1,
            $content
        );
    }
    
    function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</p>';
        $paragraphs = explode( $closing_p, $content );
    
        foreach ( $paragraphs as $index => $paragraph ) {
            if ( trim( $paragraph ) ) {
                $paragraphs[$index] .= $closing_p;
            }
    
            if ( $paragraph_id === $index + 1 ) {
                $paragraphs[$index] .= $insertion;
            }
        }
    
        return implode( '', $paragraphs );
    }

    It works fine and no errors, I want to know if my function is correct and safe. if so, that function should be updated.

  • Hi there,

    Your code looks solid 🙂

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.