最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Display meta box dropdown (from custom post type) in the page post type

programmeradmin1浏览0评论

I am trying to add a meta box to the "page" post type, in which I succeeded. In my meta box I would like to display a dropdown with titles from an other custom post type (named "Albums"). I also succeeded in that, but once I select a specific album in the dropdown and save the page, it changes the page permalink to the permalink of the chosen album.

<?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.
     }
}

I am trying to add a meta box to the "page" post type, in which I succeeded. In my meta box I would like to display a dropdown with titles from an other custom post type (named "Albums"). I also succeeded in that, but once I select a specific album in the dropdown and save the page, it changes the page permalink to the permalink of the chosen album.

<?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.
     }
}
Share Improve this question edited Feb 25, 2018 at 15:04 Max Yudin 6,3782 gold badges26 silver badges36 bronze badges asked Feb 25, 2018 at 10:59 DannyDanny 136 bronze badges 2
  • I try your code and I don't have the same problem. but you don't use correctly the_title for selecting the saved element. it would be easier to generate the "select" with a loop on a post array : codex.wordpress/Function_Reference/get_posts – mmm Commented Feb 25, 2018 at 11:30
  • Thanks. Hmm it keeps on changing the permalink. I tried an array and foreach (instead of the while->have_posts). Frustrating.. Any suggestions? – Danny Commented Feb 25, 2018 at 12:01
Add a comment  | 

2 Answers 2

Reset to default 1

Here's the updated meta box callback function. I've used get_posts() instead of WP_Query as get_posts() is more performant as well as easy to use in this case. And removed get_post_custom() as it'll fetch all the custom metadata when you don't need them. So, I've replaced that with get_post_meta(). Hope your dropdown will work as expected now.

I'd suggest you save post id (album id) instead of the title.

function meta_box_album_callback( $post ) {
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );

    $mytheme_custom_select = get_post_meta( $post->ID, 'mytheme_custom_select', true );
    $albums = get_posts( array(
        'post_type'      => 'albums',
        'post_status'    => 'publish',
        'posts_per_page' => -1
    ) );
    ?>

    <p>
        <label for="mytheme_custom_select">Select album:</label><br>
        <select id="mytheme_custom_select" name="mytheme_custom_select">
            <option value="">Selecht an album...</option>
            <?php foreach ( $albums as $album ) : ?>
                <option value="<?php echo esc_attr( $album->post_title ); ?>" <?php selected( $mytheme_custom_select, esc_attr( $album->post_title ) ); ?>><?php echo esc_html( $album->post_title ); ?></option>
            <?php endforeach; ?>
        </select>
    </p>

    <?php
}

The above code is right but there is no save dropdown option. For save you can follow below code

function meta_box_album_callback( $post ) {
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );

    $mytheme_custom_select = get_post_meta( $post->ID, 'mytheme_custom_select', true);
    $albums = get_posts( array(
        'post_type'      => 'albums',
        'post_status'    => 'publish',
        'posts_per_page' => -1
    ) );
    ?>

    <p>
        <label for="mytheme_custom_select">Select album:</label><br>
        <select id="mytheme_custom_select" name="mytheme_custom_select">
            <option value="">Selecht an album...</option>
            <?php foreach ( $albums as $album ) : ?>
                <option value="<?php echo esc_attr( $album->post_title ); ?>" <?php selected( $mytheme_custom_select, esc_attr( $album->post_title ) ); ?>><?php echo esc_html( $album->post_title ); ?></option>
            <?php endforeach; ?>
        </select>
    </p>

    <?php
}

// Here you can save choose value.

$mytheme_custom_select = $_POST['mytheme_custom_select'];
    update_post_meta( $post_id, 'mytheme_custom_select', $mytheme_custom_select );
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>