Site logo

Archived topic

Insert featured image in content (before last H2 + caption)

7 replies · Started by webmasterla-montgolfiere-fr on February 6, 2023

Viewing posts 1–8 of 8

Hi to the team !

Many thanks again for your work and I'm really satisfied with Generatepress ;) Contratulations !

I read this really interesting post and works fine :
https://generatepress.com/forums/topic/decrease-the-spacing-between-the-headline-and-image/#post-1672071

I would like to know if there is a way to :
- Insert the featured image automatically before the last H2 in the content
- and with the caption.

Many thanks again !

Hi there,

injecting 'code' into the content using the the_content filter hook can get really complicated.
Does it have to be before the LAST H2 ?

Ah ok I understand.

Does it have to be before the LAST H2 ?

It's definitely the best option for the reader and for consistency and hierarchical logic.

Hope it's possible, if not I have to do manually for 800 contents :)

I sent my message to much fast ...

Just forgot: many thanks David !

Try this method:

function featured_image_after_last_h2($content) {

    // abort if not single post or content has no H2
    if ( ( !is_singular('post') ) || ( strpos($content, '<h2') === FALSE ) ) {  
        return $content; 
    }
    // get the post thumbnail and caption
    global $post;
    $feat_img = get_the_post_thumbnail($post->ID, 'post-single');
    $feat_caption = get_the_post_thumbnail_caption($post->ID);
    
    // set the counter target to last H2
    $heading_count = substr_count($content, '<h2>'); 

    // loop through content and insert the HTML
    $content = explode("<h2", $content);
    $new_content = '';

    for ($i = 0; $i < count($content); $i++) {
        if ($i == $heading_count) {
            $new_content .= '<figure class="incontent-featured-image">' . $feat_img . '<figcaption>' . $feat_caption . '</figure>';
        }
        if($i>0) {
          $new_content.= "<h2".$content[$i];
        } else {
          $new_content.= $content[$i];
        }
    }

    return $new_content;
}
add_filter('the_content', 'featured_image_after_last_h2');

Wow it works like a charm :)

It's so nice to give me the solution ! Hope it took not so much time and could help others users :)
Great team for a great theme ;)

Many thanks again David !

For reference and kudos, i found the code for before H2 here:

https://stackoverflow.com/q/61668699

And then revised that to find the last H2 to insert before :)

Glad to hear it is working!

Great to link to the code ;)
🙏
Many thanks again !
Have a great day !

This archived topic is closed to new replies.