Last active
April 1, 2019 00:47
-
-
Save tradesouthwest/892ff04049cb83d90553e402ace932c4 to your computer and use it in GitHub Desktop.
wordpress use selected in a dropdown list for custom post type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Demonstration uses all cpt posts in a dropdown field to select | |
* a featured listings to callback in a function | |
* @param $wpselected_ string References a plugin option Setting. | |
*/ | |
function wpselected_featured_listing_cb() | |
{ | |
$post_type = 'wpselected_post'; | |
$options = get_option('wpselected_lists'); | |
// select(ed)_id will be a custom option outside of this function. | |
$wpselected_select_id = $options['wpselected_featured_listing']; | |
// Avoid ending up with no string value by setting a default value | |
if( $wpselected_select_id == '' ) $wpselected_select_id = 0; | |
/** | |
* Sets up a list of cpt posts to do foreach with | |
* @param $label string Optional | |
*/ | |
$post_type_object = get_post_type_object($post_type); | |
$label = $post_type_object->label; | |
$posts = get_posts( array( | |
'post_type' => $post_type, | |
'post_status' => 'publish', | |
'suppress_filters' => false, | |
'posts_per_page' => -1 | |
) | |
); | |
?> | |
<label class="olmin"><?php esc_html_e( 'Listing at top home page.', | |
'wpselected' ); ?></label> | |
<select name="wpselected_lists[wpselected_featured_listing]" | |
id="ol_featured_listing">'; | |
<option value="0"><?php echo esc_html( $label ); ?></option> | |
<?php | |
/** | |
* `selected` magic in use | |
*/ | |
foreach ($posts as $post) { | |
echo '<option value="' . $post->ID . '"' | |
. selected( $onlist_select_id, $post->ID ) . '>' | |
. $post->post_title . '</option>'; | |
} | |
echo '</select>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment