Search code examples
phpwordpressifttt

Delete part of src after a certain character


I am using IFTTT with Wordpress, so every time that I create a post on instagram, the recipe creates a post on Wordpress.

The code that IFTTT creates:

<div>
   <img src='https://scontent.cdninstagram.com/t51.2885-15/sh0.08/e35/12724750_1719815604930604_2078818546_n.jpg?ig_cache_key=MTE5MTQxNTkwMjE5ODM2NzYwOQ%3D%3D.2' style='max-width:600px;' /><br/>
   <div>
      <a href="http://ift.tt/1XKFC24Q7" target="_blank">See</a>
   </div>
</div>

For some reason a plugin that I am using to add this image like featured image, doesn't like this end of the src of the image, so I need to delete the code after ".jpg":

"?ig_cache_key=MTE5MTQxNTkwMjE5ODM2NzYwOQ%3D%3D.2").

I've found a Wordpress filter that modify the post before save. So I tried this code but this delete all the other code after the ?

add_filter( 'wp_insert_post_data' ,  __NAMESPACE__ . '\\filter_post_data' , '99', 2 );

function filter_post_data( $data , $postarr ) {

  $data['post_content'] = substr( $data['post_content'], 0, strpos( $data['post_content'], "?")); delete all after ?

  return $data;
}

How can say delete everything after the question mark (?) but ONLY inside the src of the img tag?

This is the reference for $data['post_content']:

https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data


Solution

  • Thanks you all, I solved with this code:

    add_filter( 'wp_insert_post_data' ,  __NAMESPACE__ . '\\filter_post_data' , '99', 2 );
    
    function filter_post_data( $data , $postarr ) {
        $data['post_content'] = preg_replace('/(\?.*)(?=\' style)/','', $data['post_content']);
        return $data;
    }
    

    but now I have another issue, how can I sayto apply this filter ONLY if the category is "Instagram"?

    this condition seems doesn't work:

    add_filter( 'wp_insert_post_data' ,  __NAMESPACE__ . '\\filter_post_data' , '99', 2 );
    
    function filter_post_data( $data , $postarr ) {
    
      if ( in_category('instagram') ) {
        $data['post_content'] = preg_replace('/(\?.*)(?=\' style)/','', $data['post_content']);
        return $data;
      }
    }
    

    thanks