Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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;
}
share|improve this answer
    
Thank you very much, this has removed the notices and everything still works as expected. –  Andrew Oct 5 '12 at 0:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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