Global custom meta box

时间:2012-02-09 作者:ZaneDeFazio

我试图在WordPress中为多个自定义帖子类型创建一个自定义元框,而不创建重复的代码。

目前我有:

add_meta_box(\'adv_form_box1\', \'Advanced Form\', \'adv_form1\', \'custom-post-type1\', \'side\', \'high\');
add_meta_box(\'adv_form_box2\', \'Advanced Form\', \'adv_form2\', \'custom-post-type2\', \'side\', \'high\');
add_meta_box(\'adv_form_box3\', \'Advanced Form\', \'adv_form3\', \'custom-post-type3\', \'side\', \'high\');

function adv_form1() {
global $post;
$custom = get_post_custom($post->ID);
$filename = $custom[\'filename\'][0]; ?>
<label>Filename:</label> (this field is required)<br/><input name="filename" size="70" value="<?php echo $filename; ?>" />
<?php }

function adv_form2() {
global $post;
$custom = get_post_custom($post->ID);
$filename = $custom[\'filename\'][0]; ?>
<label>Filename:</label> (this field is required)<br/><input name="filename" size="70" value="<?php echo $filename; ?>" />
<?php }

function adv_form3() {
global $post;
$custom = get_post_custom($post->ID);
$filename = $custom[\'filename\'][0]; ?>
<label>Filename:</label> (this field is required)<br/><input name="filename" size="70" value="<?php echo $filename; ?>" />
<?php }
我感觉好像在创建一堆额外的不需要的代码。是否可以将元框设置为“全局”以用于所有帖子类型?

3 个回复
最合适的回答,由SO网友:Ian Dunn 整理而成

除了其他答案之外,您还可以通过在类型数组中循环来进一步改进它,而不是在每次添加新类型时手动添加新的add\\u meta\\u box()行。

$postTypes = array( \'custom-post-type1\', \'custom-post-type2\', \'custom-post-type3\' );
foreach( $postTypes as $pt )
    add_meta_box( \'adv_form_box1\', \'Advanced Form\', \'adv_form1\', $pt, \'side\', \'high\' );

SO网友:EAMann

您正在创建一系列额外的工作。

与其为每个post类型创建单独的回调函数,不如使用相同的回调函数。因此:

add_meta_box(\'adv_form_box\', \'Advanced Form\', \'adv_form\', \'custom-post-type1\', \'side\', \'high\');
add_meta_box(\'adv_form_box\', \'Advanced Form\', \'adv_form\', \'custom-post-type2\', \'side\', \'high\');
add_meta_box(\'adv_form_box\', \'Advanced Form\', \'adv_form\', \'custom-post-type3\', \'side\', \'high\');

function adv_form() {
    global $post;
    $custom = get_post_custom($post->ID);
    $filename = $custom[\'filename\'][0]; 
?>
<label>Filename:</label> (this field is required)<br/><input name="filename" size="70" value="<?php echo $filename; ?>" />
<?php 
}

SO网友:Stephen Harris

对您可以使用相同的回调函数:

add_meta_box(\'adv_form_box1\', \'Advanced Form\', \'adv_form1\', \'custom-post-type1\', \'side\', \'high\');
add_meta_box(\'adv_form_box2\', \'Advanced Form\', \'adv_form1\', \'custom-post-type2\', \'side\', \'high\');
add_meta_box(\'adv_form_box3\', \'Advanced Form\', \'adv_form1\', \'custom-post-type3\', \'side\', \'high\');
(我保持ID不变,但对于每种帖子类型,ID也可能相同)。

结束

相关推荐

Get fields from metabox array

在我的函数中,我正在用自定义字段注册多个元数据库。例如,单个metabox数组如下所示:在函数中。php$meta_boxes[] = array( \'id\' => \'general_info\', \'title\' => \'General Information\', \'pages\' => array(\'post\', \'page\', \'link\'), // multiple post types, accept