0

I hope someone can help me.

  • I have a custom post type called Site members with slug site-members
  • I have a custom field (which is a select field) called aab-ew-select-visible and in this field users can select either of the options display or hide
  • The taxonomy slug is test-all-members-cpt-tax
  • The term slug is test-all-members-ew-tax

Whenever anyone posts a new post to this custom post type, they can choose to either 'hide' or 'display' a section of their post on the website. If they choose to 'display' with the select field, then they should automatically be assigned to the taxonomy term 'test-all-members-ew-tax' mentioned above.

If anyone can help with the code for this, that would be massively appreciated.

Thank you for your time, Andrew

1 Answer 1

0

The following should do what you need:

add_action ('save_post_site-members', 'add_term') ;

function
add_term ($post_id)
{
    if (defined ('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return ;
        }

    $meta_key = 'aab-ew-select-visible' ;
    $tax = 'test-all-members-cpt-tax' ;
    $term_slug = 'test-all-members-ew-tax' ;

    $meta_value = isset ($_REQUEST[$meta_key]) ? $_REQUEST[$meta_key] : '' ;
    if ('display' == $meta_value) {
        $term = get_term_by ('slug', $term_slug, $tax) ;
        if ($term) {
            wp_set_object_terms ($post_id, $term->term_id, $tax, true) ;
            }
        }

    return ;
}
7
  • Thanks so much @Paul - but for some reason that hasn't worked either. I just created a new post, selected 'display' as the value of the field, and the term wasn't assigned on saving the post. Do you know anywhere I could be going wrong? I really appreciate your time - thank you. Commented Feb 18, 2017 at 16:45
  • I just edited my answer, with a more direct way of setting $meta_value. The original code assumed that you had some other func that hooked into save_post-site-members that was storing the meta...and if the func I wrote was being called before that other func then it wouldn't work. The revised code should be fine. Commented Feb 18, 2017 at 17:06
  • Thanks for updating the code. I just ran it again, then created a new post, and still it didn't work. Feel cursed Commented Feb 18, 2017 at 17:19
  • I've tested (both versions of) my code and it works in a test env I have. So, seeing a little bit more of your code would be helpful in figuring out why it's not working for you. Commented Feb 18, 2017 at 17:26
  • You might also try writing $meta_value & $term to a log file so that you can see what their values are when the save_post action is fired (i.e., maybe that term doesn't actually exist). Commented Feb 18, 2017 at 17:29

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.