Consider that when you add a metabox, nothing force you to save the value in post meta field, you can save a global option from metabox as well.
function my_add_custom_box() {
$screens = array( 'post' ); // add or replace with your cpt name
foreach ( $screens as $screen ) {
add_meta_box(
'my_sectionid', __( 'Featured Monthly Product', 'my_textdomain' ), 'my_inner_custom_box',
$screen
);
}
}
add_action( 'add_meta_boxes', 'my_add_custom_box' );
function my_inner_custom_box( $post ) {
wp_nonce_field( 'my_inner_custom_box', 'my_inner_custom_box_nonce' );
$value = (int) get_option( 'featured_monthly_product') === (int) $post->ID ? 1 : 0;
echo '<label for="featured_monthly_product">';
_e( "Is this the Featured Monthly Product?", 'my_textdomain' );
echo ' <input type="checkbox" name="featured_monthly_product" value="1"' . checked(1, $value, false) . ' />';
echo '</label> ';
}
function my_save_post_option( $post_id ) {
$nonce = filter_input(INPUT_POST, 'my_inner_custom_box_nonce', FILTER_SANITIZE_STRING);
if ( ! $nonce ) return $post_id;
if ( ! wp_verify_nonce( $nonce, 'my_inner_custom_box' ) ) return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return $post_id;
$checked = (int) filter_input(INPUT_POST, 'featured_monthly_product', FILTER_SANITIZE_NUMBER_INT);
if ($checked > 0) {
update_option( 'featured_monthly_product', $post_id );
} elseif ( (int) $post_id === (int) get_option('featured_monthly_product') ) {
delete_option('featured_monthly_product');
}
}
add_action( 'save_post', 'my_save_post_option' );
You don’t explain what you want to save on that custom value, so I guessed you want to store the post ID, change the code accordingly if not.
The code above show a metabox with a checkbox. When you save post, if the checkbox is checked, the current post id is saved into option featured_monthly_product
.
If the checkbox is uncheched and the post was the featured monthly product the option is deleted.
If you want to globalize that value, use
add_action('init', 'globalize_featured_monthly_product');
function globalize_featured_monthly_product() {
global $featured_monthly_product;
$featured_monthly_product = get_option('featured_monthly_product');
}
After that, wherever you need the featured monthly product id, just use:
global $featured_monthly_product;
// just an example:
echo "The featured monthly product id is: " . $featured_monthly_product;