使用函数测试短码。404页面抛出PHP通知

时间:2012-10-04 作者:Andrew

我正在使用以下函数(不记得在哪里找到它,但我认为它是由pippin编写的,多亏了他)来测试一个短代码。

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;
}
问题是,在404页这样的页面上,我会遇到以下错误:

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
第49行中的主题函数是上述函数的这一行

if (  stripos( $post_to_check->post_content, \'[\' . $shortcode ) !== false ) {
如果我删除函数调用if( has_shortcode(\'gallery\') ) ... 从另一个文件中,这两个错误消失了。我相信这两者是相关的,如果我修复了该功能,它将同时清除它们。我可以“有点”理解为什么会这样。。。我的理解是,在404页面上没有$post变量集,因此我需要修改函数以首先进行测试。我说得对吗?

1 个回复
最合适的回答,由SO网友:Abdussamad 整理而成

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;
}
结束

相关推荐

PHP Widget and do_shortcode

我正在使用PHP小部件,它允许PHP代码从小部件执行。我尝试使用此代码执行do\\u shortcode,但它没有呈现<?php $lat = get_field(\'woo_maps_lat\'); $long = get_field(\'woo_maps_long\'); echo do_shortcode(\'[forecast location=\"\' . $lat .\',\'.$long. \'\" measurement=\\\'C\\\']\');