You got it quite right, but with a few minor problems.
First, please use a uniqe prefix for your functions and values - opacity
or meta_save
are quite generic and could be used by other authors.
Second, the part where you get the meta opacity was missing, I added it for you - just retrieve the meta value from the current post.
Third, I then created a function to loop throug the different opacities. I too used the selected()
function, but with the third parameter (echo) set to false
- so selected returns my value instead of echoing it. This is a handy WordPress function to create such options and stuff like that.
That's it.
Just be sure to adjust your code when you use the post thumbnail, and be sure to get the f711_opacity
meta value from the $post
object, not from the thumbnail itself, as it is saved to the post.
add_filter( 'admin_post_thumbnail_html', 'f711_add_something_to_feature_thumb_box', 10, 2 ); //same as before
function f711_add_something_to_feature_thumb_box( $myhtml, $post_id ) {
$selected_option = get_post_meta( get_the_ID()$post_id, 'f711_opacity', true ); // get the current value
for ( $i = 0; $i <= 1; $i = $i + 0.1 ) { //loop from 0 to 1 in 0.1 increments
$selects .= '<option value="' . $i . '" ' . selected( $selected_option, $i, false ) . '>' . $i . '</option>'; //add a option field, and select it if it is the one saved before
}
//create the return html, with the selects created before
return $myhtml .= 'Opacity:
<form>
<select name="f711_opacity">
' . $selects . '
</select>
</form>';
}
// function and action to save the new value to the post
function f711_meta_save( $post_id ) {
if( isset( $_POST[ 'f711_opacity' ] ) ) {
update_post_meta( $post_id, 'f711_opacity', sanitize_text_field( $_POST[ 'f711_opacity' ] ) );
}
}
add_action( 'save_post', 'f711_meta_save' );