我试图在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 }
我感觉好像在创建一堆额外的不需要的代码。是否可以将元框设置为“全局”以用于所有帖子类型?
最合适的回答,由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也可能相同)。