Search code examples
phpwordpressreturnshortcode

How to return a certain html tag in php


Sorry if this is a really stupid question. I am just starting to learn PHP and am probably jumping the gun a bit.

I am writing a very 'simple' wordpress plugin which has a custom post type and takes the content from it and returns it on the homepage with a shortcode. Below is the part of the code that handles the shortcode.

add_shortcode("new-tub", "new_tub_short");

function new_tub_short() {
  $post_id = 87;

  return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . get_post_field('post_content', $post_id) . '</a>';
}

So currently it wraps a link around the content of the post. All that is in the post will be an image, however, I would like to make it fool proof so it doesnt include another link and paragraph tag.

My question is, is it possible to search for the img tag within that post and return that only?

Thanks in advance, Alex


Solution

  • You can do this by using strip_tags. Try this,

    add_shortcode("new-tub", "new_tub_short");
    
    function new_tub_short() {
      $post_id = 87;
    
      return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . strip_tags(get_post_field('post_content', $post_id), '<img>') . '</a>';
    }
    

    http://php.net/manual/en/function.strip-tags.php