ThemeForest

Custom meta field checkbox

47 posts
  • Has been a member for 2-3 years
  • Bought between 1 and 9 items
virgild says

So I’m trying to create a meta box checkbox but I can’t get it to function..

the code I’m using is

 echo '<label for="myplugin_new_field">' . __("Description for this field", 'myplugin_textdomain' ) . '</label> ';
  echo '<input type="checkbox" name="myplugin_new_field" id="myplugin_new_field" value="yes"';
                                    if ( get_post_meta('myplugin_new_field', true ) == "yes" )
                                        echo ' checked="checked"';
                                    echo '" style="width: auto;" />';
}

The checkbox appears in edit post pages without any errors. I check it but after I update the post it becomes unchecked.

Not sure what I’m doing wrong here.. will appreciate any kind of guidance!

2 years ago
407 posts
  • Has been a member for 3-4 years
  • Grew a moustache for the Envato Movember competition
  • Exclusive Author
  • Sold between 100 000 and 250 000 dollars
  • Elite Author
  • Bought between 1 and 9 items
  • Portugal
  • Referred between 10 and 49 users
unisphere says

I believe the code above only displays the checkbox, you need to have a way for WP to store it in the DB (wp_options table).

First register a function for saving the meta data:

function save_postdata( $post_id ) {

    // Get the $_POST meta data and save it with update_option function

}

Then hook that function to the save post action like so:

add_action('save_post', 'save_postdata');

Hope it helps, best regards, UniSphere

2 years ago
47 posts
  • Has been a member for 2-3 years
  • Bought between 1 and 9 items
virgild says

Thanks for the suggestion! I’m using the Wordpress meta box function reference as the frame work

http://codex.wordpress.org/Function_Reference/add_meta_box

It contains the code you provided but it still doesn’t work..

Maybe I should use arrays?

2 years ago
280 posts
  • Has been a member for 3-4 years
  • Interviewed on the Envato Notes blog
  • Exclusive Author
  • Sold between 250 000 and 1 000 000 dollars
  • Elite Author
  • Bought between 50 and 99 items
  • Referred between 100 and 199 users
imaginem says

The problem could be around this code.

if ( get_post_meta('myplugin_new_field', true ) == "yes" ) echo ' checked="checked"';

maybe the following might resolve it

if ( get_post_meta($post->ID,'myplugin_new_field', true ) == "yes" ) echo ' checked="checked"';

Cheers

2 years ago
47 posts
  • Has been a member for 2-3 years
  • Bought between 1 and 9 items
virgild says

Thanks for the reply! That doesn’t seem to work either :( I guess I’ll just use arrays. I was hoping to achieve it with the more minimal function reference.

2 years ago
by
by
by
by
by