For saving the checkbox, one easy way to check, if the checkbox was checked is to use empty()
function. The checkbox key and value exists in $_POST
only, if it was checked when the form was submitted.
For example,
function snup_save_meta($post_id) {
// nonce check etc.
// save text
$snupText = $_POST['snuptext'] ?? '';
update_post_meta(
$post_id,
'snuptext',
$snupText ? sanitize_textarea_field( $snupText ) : ''
);
// save checkbox
$snupCheckChecked = ! empty( $_POST['snup_check'] );
update_post_meta(
$post_id,
'snup_check',
$snupCheckChecked ? '1' : ''
);
}
Then on your posts loop check, if the post has the meta value set or not.
// Option 1
function snupwidget_upcoming_posts() {
// code...
foreach ( $the_query->posts as $post ) {
// Skip, if not checked
if ( empty( get_post_meta( $post->ID, 'snup_check', true ) ) ) {
continue;
}
// code...
}
}
Another option is to modify your query to only include posts that should be displayed in the first place by using a meta query.
// Option 2
function snupwidget_upcoming_posts() {
$output = '';
// The query to fetch future posts
// Limit query to posts with defined meta value
// Not tested, but should probably work like this..
$the_query = new WP_Query(array(
// params..
'meta_query' => array(
'key' => 'snup_check',
'value' => '1',
'type' => 'numeric',
),
));
// code...
}
But using post meta this way might cause performance issues in the long run. A better option would be to use a (private) utility taxonomy to group posts, that should be displayed by the widget.
Tom J Nowell has written couple of great articles about this, if you're interested in learning more.
UPDATE
You can use checked() on the checkbox input to mark it checked based on the saved post meta.
<?php
$snupCheck = get_post_meta( $post->ID, 'snup_check', true );
?>
<input type="checbox" name="snup_check" value="1" <?php checked( $snupCheck, 1, true ); ?>>