循环遍历 类 中的数组以创建 wordpress 元数据框

Looping through arrays within classes to create wordpress metaboxes

我的 Wordpress functions.php 中有一个 class。最终它会在插件文件夹中结束,但一次一步。下面是它的透视图:

class metaboxClass {

    $them_meta_boxes = array (
        array (
            "1a_myplugin_box_id_1",
            "1b_Custom Meta Box Title 1"
        ),
        array (
            "2a_myplugin_box_id_2",
            "2b_Custom Meta Box Title 2"            
        )
    );

    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
    }

    public function add_meta_box( $post_type ) { 

        $post_types = array( 'page', 'my_cpt' );
        if ( in_array( $post_type, $post_types )) { // *** IF $POST_TYPE IS IN THE ARRAY $POST_TYPES

            foreach ($this->them_meta_boxes as $level_1) {

                add_meta_box (
                foreach ($this->level_1 as $level_2) {
                    echo $level_1 . ",";
                }
                array( $this, 'render_form'),
                $post_type
                )
            }
        }
    }
}

正如您从上面看到的,我正在尝试使用数组中的信息构造 add_meta_boxes 函数的各种迭代。

我觉得这里有很多问题,我一次要解决一个问题,但第一个是当一个对象从 class 实例化时,我得到:"syntax error, unexpected 'foreach' "。我知道这通常是由于缺少分号引起的。在这种情况下,分号存在并且是正确的。我觉得这与阵列的放置有关,但当它放在外面时我遇到了类似的问题。任何人都可以给我任何指示 - 我对 OO 的世界还很陌生 PHP,而且我还不熟悉 wordpress 后端,所以任何指示都将不胜感激。

提前致谢, 史蒂夫

您不能将 foreach 循环作为参数传递给函数。首先构造您的参数字符串,然后将构造的字符串作为参数传递给您的 add_meta_box 函数。

尽管如此,我还是不确定您要调用什么,因为您的 add_meta_box 函数只接受一个参数。

已整理记录...结果如下:

class initialise_meta_boxes {

    public $meta_boxes_array = array (
        array (
            "1a_myplugin_box_id_1",
            "1b_Custom Meta Box Title 1",
            "render_dropdown"
        ),
        array (
            "2a_myplugin_box_id_2",
            "2b_Custom Meta Box Title 2",
            "render_dropdown"       
        )
    );


    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
        add_action( 'save_post', array( $this, 'save' ) );
    }

    public function make_meta_box($meta_id, $meta_title, $meta_callback) { 
        return add_meta_box ($meta_id, $meta_title, $meta_callback, $post_type );
    }

     public function add_meta_box( $post_type ) { // *** $post_type is global variable!!!
        $post_types = array( 'page', 'my_cpt' );
        if ( in_array( $post_type, $post_types )) { // *** IF $POST_TYPE IS IN THE ARRAY $POST_TYPES

            foreach ($this->meta_boxes_array as $value) {
                    $this->make_meta_box($value[0], $value[1], array( $this, $value[2]));
            }
        }
    }
}