Adding the following script to the function.php file in WordPress:
add_action( 'add_meta_boxes', 'rating_select_box' );
function rating_select_box() {
add_meta_box(
'rating_select_box', // id, used as the html id att
__( 'Select rating:' ), // meta box title, like "Page Attributes"
'rating_select_cb', // callback function, spits out the content
'post', // post type or page. We'll add this to posts only
'side', // context (where on the screen
'low' // priority, where should this go in the context?
);
}
function rating_select_cb( $post )
{
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last">
<span id="timestamp">'
. '<label>Select a rating:<br></label>';
$selected = ($value == $result->post_name) ? ' selected="selected" ' : null;
echo '<select name="rating">';
echo '<option value="" default="default"> None... </option>';
echo '<option value="0" '.$selected.'> G â Suitable for all audiences </option>';
echo '<option value="1" '.$selected.'> PG â Possibly offensive, usually for audiences 13 and above </option>';
echo '<option value="2" '.$selected.'> R â Intended for adult audiences above 17 </option>';
echo '<option value="3" '.$selected.'> X â Even more mature than above </option>';
echo '</select>';
echo '</span></div>';
}
add_action( 'save_post', 'save_metadata');
function save_metadata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if( empty($postid) ) return false;
if ( is_null($_REQUEST["rating"]) ) {
delete_post_meta($postid, 'rating');
} else {
update_post_meta($postid, 'rating', $_REQUEST['rating']);
}
}
Will add a box in the post page with a drop down list. I want the default option to be on None...
so I added a default="default"
to that option, but it does not work. By default, the highest number value is selected, in this case, it is X â Even more mature than above
.
What am I doing wrong? How can I make it so that the None...
option is selected by default?
In a
select
list, the correct way to “select” an option is withselected="selected"
, notdefault="default"
. Changing your ‘None’ option to the following should fix it:However, you’re not dynamically creating your
select
list, you’re just outputting a full list and you’ll run into issues selecting the other values too. To fix this, if the options won’t be changing, you can put them in an array to loop through them. You can modify yourrating_select_cb()
method with the following new code to achieve this:This method will default-select the “None” option if the selected
$value
is not in the available list of ratings. After that, it will loop through each rating and output it as an option. If the rating’s$id
matches the selected$value
, it will be marked as selected.You should use it like this: