4

My code is not working, it does not add the taxonomy

add_action('init', 'post_test', 10);
function post_test() {
    $empty = get_page_by_title('Produto teste', OBJECT, 'produtos');
    if(empty($empty)) {
        $insert_post = array(
            'post_status' => 'publish',
            'post_type' => 'produtos',
            'post_title' => 'Produto teste',
        );
        $post_id = wp_insert_post($insert_post);
        if ($post_id) {
            wp_set_post_terms($post_id, array('metais'), 'categoria-produtos'); // tag metais id is 108
        }
        add_post_meta($post_id, 'fornecedores', '5948'); // id do fornecedor
        add_post_meta($post_id, '_fornecedores', 'field_52377232eb265');
    }
}

why not work?

1 Answer 1

22

As stated in the wp_set_post_terms Comment:

This function will only work on the native post type. For a taxonomy on a custom post type use wp_set_object_terms()

wp_set_object_terms

5
  • Thanks brother, tihis code woks! : wp_set_object_terms($post_id, array('metais'), 'categoria-produtos', true); // tag metais id is 108 thnks thnks
    – Raank
    Sep 17, 2013 at 19:17
  • This is not the case any more. For WP 5+ you can use both even for custom post types. Feb 10, 2019 at 9:23
  • 3
    Now the Codex says : This function will work on any post type. Alternatively, wp_set_object_terms() can be used. Feb 10, 2019 at 9:29
  • @ToleaBivol Cannot confirm that, lost 4 hours searching why custom taxonomy was not set, found out it's because there's a different between wp_set_post_terms and wp_set_object_terms
    – n.r.
    Aug 22, 2020 at 21:05
  • Classic Wordpress quality code.
    – marek.m
    Feb 8, 2021 at 8:16

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.