0

I'm looking for a simple function to automatically add a specific tag to a post if a checkbox is checked.

For example: When creating a post there is a checkbox that says:

"Add example tag to post"

If you check it, the post will be given an "example" tag.

I have the checkbox set up, it's just adding the tag when checked which is causing me some difficulties.

Here is the function in my child theme function file that is causing the problem:


add_action( 'wp_set_object_terms' , 'add_example_tag');

function add_example_tag() {
     global $post;

$example = get_post_meta( $post->ID, '_example', true );
  if ( $example ) {
wp_set_post_tags('example', true );
}
}

Any help is greatly appreciated.

Cheers.

1 Answer 1

0

If I understand what you want I would call it on the save_post hook: https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

So the code would be something a little like:

    function wphuyeh8_save_post_tag( $post_id, $post, $update ) {
    // If example is set and not false
    if($_REQUEST['_example']):
        // set the tag
            wp_set_post_tags( $post_ID, 'example', true );
    else:
        // remove the tag if the checkbox is not checked
            wp_remove_object_terms( $post_id, 'example', 'post_tag' );
    endif;
}
add_action( 'save_post', 'wphuyeh8_save_post_tag', 10, 3 );

Though this is untested, and taking a second glance it will try and remove the tag on every post save unless it is checked so you may want to add in some checking for a post type or something.

1
  • Thanks Toby! It helped. I realized it's a tag for a custom post type so I'm playing around with finding the post-type tag taxonomy.
    – David
    Aug 26, 2015 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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