PHP警告:为Foreach提供的参数无效

时间:2016-08-09 作者:Martin Greenwood

我的wp\\U调试日志文件中出现此错误:[2016年8月9日11:05:05 UTC]PHP警告:为中的foreach()提供的参数无效。。。wp内容/主题/神话/自定义帖子类型/CPT。php第23行

我似乎不明白为什么这会给那个错误。。。

问题代码如下

$cpts = array(
    array(\'shows\',\'Show\',\'Shows\',\'dashicons-tickets-alt\',array(\'title\',\'editor\',\'thumbnail\',\'comments\')),
    array(\'people\',\'Person\',\'Team\',\'dashicons-groups\',array(\'title\',\'editor\',\'thumbnail\')),
    array(\'cast\',\'Cast & Crew\',\'Cast & Crew\',\'dashicons-universal-access\',array(\'title\',\'editor\',\'thumbnail\')),
    array(\'brochures\',\'Brochure\',\'Brochures\',\'dashicons-book\',array(\'title\',\'editor\',\'thumbnail\')),
    array(\'jobs\',\'Job\',\'Jobs\',\'dashicons-businessman\',array(\'title\',\'editor\',\'thumbnail\')),
    array(\'businesses\',\'Business\',\'Businesses\',\'dashicons-building\',array(\'title\',\'editor\',\'thumbnail\')),
    array(\'prices\',\'Price List\',\'Price Lists\',\'dashicons-money\', array(\'title\')),
);

function cpts_register() {

    global $cpts;

    foreach($cpts as $cpt){

        $cpt_wp_name = $cpt[0];
        $cpt_singular = $cpt[1];
        $cpt_plural = $cpt[2];
        $cpt_image = $cpt[3];
        $cpt_suports = $cpt[4];

        $labels = array(
        \'name\' => _x($cpt_plural, \'post type general name\'),
        \'singular_name\' => _x($cpt_singular, \'post type singular name\'),
        \'add_new\' => _x(\'Add New\', $cpt_wp_name),
        \'add_new_item\' => __(\'Add New \'.$cpt_singular),
        \'edit_item\' => __(\'Edit \'.$cpt_singular),
        \'new_item\' => __(\'New \'.$cpt_singular),
        \'view_item\' => __(\'View \'.$cpt_singular),
        \'search_items\' => __(\'Search \'.$cpt_plural),
        \'not_found\' =>  __(\'No \'.$cpt_plural.\' Found\'),
        \'not_found_in_trash\' => __(\'No \'.$cpt_plural.\' Found in Trash\'), 
        \'parent_item_colon\' => \'\',
      );
      $args = array(
        \'labels\' => $labels,
        \'public\' => true,
        \'show_ui\' => true,
        \'publicly_queryable\' => true,
        \'query_var\' => true,
        \'capability_type\' => \'post\',
        \'hierarchical\' => false,
        \'rewrite\' => true,
        \'show_in_rest\' => true,
        \'supports\' => $cpt_suports,
        \'menu_icon\'   => $cpt_image,
        );

        register_post_type($cpt_wp_name, $args );

    }

}
提前感谢您的帮助。。。

M

2 个回复
最合适的回答,由SO网友:Andy Macaulay-Brook 整理而成

主题文件包含在函数中,因此您还需要声明global $cpts 您分配它的位置。它不会自动成为全局的。

SO网友:Jbbhatti

一种修复方法是首先检查变量的类型

$items = $product->getFormats();

if (is_array($items)) {
    foreach ($items as $item) {
     // ...
    }
}