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


Looping through arrays within classes to create wordpress metaboxes

我有一个类坐在我的Wordpress函数中.php。最终它将最终出现在插件文件夹中,但一次一步。下面是它的缩影版本:

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 函数的各种迭代。

有一种感觉,这里有很多问题,我一次一个地解决它们,但首先是当一个对象从类实例化时,我得到:"语法错误,意外的'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]));
            }
        }
    }
}