问题是,为什么我的foreach循环只使用上一个数组的信息来渲染metabox?类别代码:
class CusomMetaBox {
/**
* Hook into the appropriate actions when the class is constructed.
*/
//public function __construct( $post_type, $unicname, $headline, $fieldDisc ) {
public function __construct( $array ) {
global $post;
foreach ( $array as $metabox ) {
$this->post_type = $metabox[\'post_type\'];
$this->unicname = $metabox[\'unicname\'];
$this->headline = $metabox[\'headline\'];
$this->fieldDisc = $metabox[\'field_desc\'];
add_action( \'add_meta_boxes\', array( $this, \'add_meta_box\' ) );
add_action( \'save_post\', array( $this, \'save\' ), 1, 2);
}
}
here a goes other methods that render and save metaboxes...
public function add_meta_box() {
add_meta_box(
$this->unicname
,$this->headline
,array( $this, \'render_meta_box_content\' )
,$this->post_type
,\'advanced\'
,\'high\'
);
}
这是函数中的函数。初始化类的php:
function call_createCustomMetaBox() {
new CusomMetaBox( array(
\'eventdata\'=>array(
\'post_type\'=>\'event\',
\'unicname\'=>\'eventdata\',
\'headline\'=>\'Event Date\',
\'field_desc\'=>\'Enter the date of your event\'
),
\'eventplace\'=>array(
\'post_type\'=>\'event\',
\'unicname\'=>\'eventplace\',
\'headline\'=>\'Place of the event\',
\'field_desc\'=>\'Enter address of the event\'
),
\'productcost\'=>array(
\'post_type\'=>\'product\',
\'unicname\'=>\'productcost\',
\'headline\'=>\'Cost of the product\',
\'field_desc\'=>\'Enter the cost of the product. For example: 50.00$ per hour\'
)
) );
}
我想不出,为什么我只得到了1个元框而不是3个(2个在事件帖子中,1个在产品帖子中)?
最合适的回答,由SO网友:WPTC-Troop 整理而成
这是因为您正在将最后一个数组元素分配给类属性post_type
,unicname
,headline
,fieldDisc
由于输入是一个数组,您会一次又一次地重写类属性,因此只有最后一个数组元素保存在那里(post_type
,unicname
,headline
,fieldDisc
).
因此,我建议将整个阵列存储在one property 或制造each property an array 这样他们就有了容纳多个值的空间
public function __construct( $array ) {
global $post;
$this->metabox_array = $array;
add_action( \'add_meta_boxes\', array( $this, \'add_meta_box\' ) );
add_action( \'save_post\', array( $this, \'save\' ), 1, 2);
}
//here a goes other methods that render and save metaboxes...
public function add_meta_box() {
//looping over all input array
foreach ( $this->metabox_array as $metabox ) {
add_meta_box(
$metabox[\'unicname\']
,$metabox[\'headline\']
,array( $this, \'render_meta_box_content\' )
,$metabox[\'post_type\']
,\'advanced\'
,\'high\'
);
}
}
您的
render_meta_box_content
通过在数组上循环,应该具有相应的内容。