I would like to know if its possible to do something like this. I have Slider custom post type and Services custom post type.
For slider posts I have created a metabox for URL value to display next to all slider posts. What I would like to do now, is to get all posts from Services custom post type, and display them in this slider post metabox as select input, so I can choose which post should the link go to.
Thanks in advance 🙂
Here is the current code:
function rm_display_slider_metabox($post) {
wp_nonce_field(basename(__FILE__), 'slider_nonce');
$slide_url_value = get_post_meta($post->ID, '_slide_url', true);
$slide_url = isset($slide_url_value) ? esc_attr($slide_url_value) : '';
$services_loop = new WP_Query(
array(
'post_type' => 'services',
'posts_per_page' => -1,
'post_status' => 'publish'
));
?>
<div class="slider meta">
<p>
<label for="slide-url"><?php _e('Select URL from the dropdown below for this slide', 'rmtheme' ); ?></label>
<br />
<select name="_slide_url">
<?php while ($services_loop->have_posts()) : $services_loop->the_post(); ?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php endwhile; ?>
</select>
</p>
</div>
<?php
}
function rm_save_slider_meta($post) {
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
if (!isset($_POST['slider_nonce']) || !wp_verify_nonce($_POST['slider_nonce'], basename(__FILE__)))
return $post_id;
if (!current_user_can('edit_post'))
return $post_id;
$allowed = array(
'a' => array(
'href' => array()
)
);
if (isset($_POST['_slide_url']))
update_post_meta($post->ID, '_slide_url', wp_kses($_POST['_slide_url'], $allowed));
}
add_action('save_post', 'rm_save_slider_meta');
add_action('add_meta_boxes', 'rm_slider_metabox');
(0. Retrieve the meta value with
get_post_custom
(in order to highlight the selected value in the select input).)Query posts with
get_posts( array( 'post_type' => 'services', 'post_status' => 'publish' ) )
Loop through the results with
foreach
and build your select input.Hook into save_post (
add_action('save_post', 'my_save_meta')
to store the selected value (withupdate_post_meta
).