我正在尝试向“页面”帖子类型添加一个元框,我成功了。在我的元框中,我想显示一个下拉列表,其中包含来自其他自定义帖子类型(名为“Albums”)的标题。我也成功地做到了这一点,但一旦我在下拉列表中选择了一个特定的专辑并保存了页面,它就会将页面永久链接更改为所选专辑的永久链接。
<?php
add_action(\'add_meta_boxes\', \'add_meta_box_album\');
function add_meta_box_album() {
add_meta_box(\'meta-box-album-id\', \'Album\', \'meta_box_album_callback\', \'page\', \'normal\', \'high\');
}
function meta_box_album_callback($post) {
$values = get_post_custom($post->ID);
$mytheme_custom_select = (isset($values[\'mytheme_custom_select\'][0]) && \'\' !== $values[\'mytheme_custom_select\'][0]) ? $values[\'mytheme_custom_select\'][0] : \'\';
wp_nonce_field(\'my_meta_box_nonce\', \'meta_box_nonce\');
?>
<p>
<label for="">Select album:</label><br>
<? $getAlbums = new WP_Query(array(
\'post_type\' => \'albums\',
));
?>
<select id="mytheme_custom_select" name="mytheme_custom_select">
<option value="">Selecht an album...</option>
<? while ($getAlbums->have_posts()):$getAlbums->the_post(); ?>
<option
value="<?php the_title($getAlbums->ID); ?>" <?php selected($mytheme_custom_select, the_title($getAlbums->ID), true); ?>><?php the_title($getAlbums->ID); ?></option>
<? endwhile; ?>
<? wp_reset_query(); ?>
</select>
<? }
add_action(\'save_post\', \'cd_meta_box_save\');
function cd_meta_box_save($post_id) {
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return;
if (!isset($_POST[\'meta_box_nonce\']) || !wp_verify_nonce($_POST[\'meta_box_nonce\'], \'my_meta_box_nonce\')) return;
if (!current_user_can(\'edit_post\', $post_id)) return;
$allowed = array(
\'a\' => array(
\'href\' => array()
)
);
if (isset($_POST[\'mytheme_custom_select\'])) { // Input var okay.
update_post_meta($post_id, \'mytheme_custom_select\', sanitize_text_field(wp_unslash($_POST[\'mytheme_custom_select\']))); // Input var okay.
}
}