问题描述
大家好,我需要在页面中为我创建的页脚和页眉posttypes 创建元数据框,在这段代码中,我为此尝试过,但我无法保存所选项目并在前端检索所选项目的 ID。
function wpdocs_register_Meta_Boxes() {
add_Meta_Box( 'Meta-Box-id',__( 'header','textdomain' ),'wpdocs_my_display_callback','page','normal','high');
}
add_action( 'add_Meta_Boxes','wpdocs_register_Meta_Boxes' );
function wpdocs_my_display_callback() {
?>
<select name="count" id="selectId" >
<?PHP
$posts = new WP_Query(array('posts_per_page' => -1,'post_type' => 'header'));
while($posts->have_posts()) : $posts->the_post(); ?>
<option id="selection" value="<?PHP echo get_the_ID(); ?>"><?PHP echo get_the_title(); ?></option>
<?PHP endwhile;
die()
?>
</select>
<?PHP
}
function wpdocs_save_Meta_Box( $post_id ) {
if (isset($_POST['selectId'])) {
update_post_Meta( $post_id,'selectId',$_POST['selectId']);
}
}
add_action( 'save_post','wpdocs_save_Meta_Box' );
解决方法
你可以像下面一样通过 postId 直接使用 echo esc_attr( get_post_meta( get_the_ID(),'selectId',true ) );
,更改您的 wpdocs_my_display_callback
函数,如下所示。
function wpdocs_my_display_callback( $post ) {
$selectId = get_post_meta( $post->ID,true );
?>
<select name="selectId" id="selectId" >
<?php
$posts = new WP_Query(array('posts_per_page' => -1,'post_type' => 'header'));
while($posts->have_posts()) : $posts->the_post(); ?>
<option id="selection" value="<?php echo get_the_ID(); ?>" <?php selected( $selectId,get_the_ID() ); ?>><?php echo get_the_title(); ?></option>
<?php endwhile;
wp_reset_query();
?>
</select>
<?php
}
,
感谢您的回答和这项工作,但需要两个元框,一个用于页眉选择,一个用于选择页脚。我使用此代码但不起作用,当注释和禁用此代码的页眉,页脚时,可以工作并保存。注释页脚部分代码时,页眉有效并已选择保存选项!!!
def validate_number(user_input):
while True:
try:
user_input = int(user_input)
return user_input
except ValueError:
print()
print("Invaild. Enter a decimal number please.")
user_input = input()