0

How can i fix a show / hide function in my plugin.

The checkbox called "snup_check" at line 257 should be standard unchecked.

If the checkbox is unchecked nothing should happens.

If the checkbox is checked this post is not gonna show up in the SNUP widget in the frontsite.

My question is:

  1. How can I save a checkbox ?
  2. How can I show / hide the output from the widget ?

The code for the project is here: https://github.com/bjovaar/SNUP

SNUP code for showing SNUP front

SNUP Code

1
  • Please don't use images of your code; edit the question and paste in the relevant snippets of the actual code. This will make it easier for us to read it and to make suggestions.
    – Pat J
    Apr 6 at 13:35

1 Answer 1

0

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 ); ?>>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.