• Resolved immortal

    (@paksociety)


    How can i change og:image to first image of post instead of Featured image?

    • This topic was modified 4 years, 10 months ago by immortal.
Viewing 1 replies (of 1 total)
  • Thread Starter immortal

    (@paksociety)

    Answering my own comment for the sake of others:
    I get it in 2 steps.

    • Get first image using function
    • Use Jetpack fallback image for post and modify it.

    Here are the codes:
    Get first image of post:

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
      $first_img = $matches[1][0];
    
      if(empty($first_img)) {
        $first_img = "Your default Fallback image URL if no image is inserted, you can change it to featured image too, if want to.";
      }
      return $first_img;
    }


    Jetpack modified code:

    function jeherve_custom_image( $media, $post_id, $args ) {
       
            $permalink = get_permalink( $post_id );
            $url = apply_filters( 'jetpack_photon_url', catch_that_image() );
         
            return array( array(
                'type'  => 'image',
                'from'  => 'custom_fallback',
                'src'   => esc_url( $url ),
                'href'  => $permalink,
            ) );
        
    }
    add_filter( 'jetpack_images_get_images', 'jeherve_custom_image', 10, 3 );
    • This reply was modified 4 years, 10 months ago by immortal.
    • This reply was modified 4 years, 10 months ago by immortal.
Viewing 1 replies (of 1 total)
  • The topic ‘OG:image as first image of Post’ is closed to new replies.