0

I'm using the following function (can't remember where I found it, but I think it was written by pippin so thanks to him) to test for a shortcode.

function has_shortcode($shortcode = '') {

   $post_to_check = get_post( get_the_ID() );

   // false because we have to search through the post content first
   $found = false;

   // if no short code was provided, return false
   if ( !$shortcode ) {
      return $found;
   }

   if (  stripos( $post_to_check->post_content, '[' . $shortcode ) !== false ) {
      // we have found the short code
      $found = true;
   }

   // return our final results
   return $found;
}

The problem is, on a page such as a 404 page I get the following errors:

Notice: Trying to get property of non-object in /wp-includes/post-template.php on line 30
Notice: Trying to get property of non-object in theme-functions.php on line 49

On theme-functions in line 49 is this line from the above function

if (  stripos( $post_to_check->post_content, '[' . $shortcode ) !== false ) {

If I remove the function call if( has_shortcode('gallery') ) ... from another file, the two errors go away. I believe the two are related and if I fix the function it will clear them both. I can "kind of" understand why this is happening... my understanding is that on the 404 page there is no $post variable set so somehow I need to modify the function to test first. Am I right?

1 Answer 1

2

Try this instead:

function has_shortcode($shortcode = '') {
  global $post;
 // false because we have to search through the post content first
 $found = false;

 // if no short code was provided, return false
 if ( !$shortcode ) {
    return $found;
 }

 if (  is_object( $post ) && stripos( $post->post_content, '[' . $shortcode ) !== false ) {
     // we have found the short code
  $found = true;
 }

// return our final results
return $found;
}
1
  • Thank you very much, this has removed the notices and everything still works as expected.
    – Andrew
    Oct 5, 2012 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.