Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

jcc5018 on "adding taxonomy term based on custom fields"

$
0
0

I have a custom post type (uc-collections) that I am setting up so that different sets of custom fields are displayed based on the type of post it is. Its one of three (collection, product, or variant).

I have everything set up in that regard, but I am thinking that when designing my templates to display different data depending on the input type, it may be easier to do it if I had the input type defined as a taxonomy.

So I would like to update my post with the corresponding taxonomy that relates to the input type.

Existing meta_key is input_type with options (collection, product, variant)

I want the taxonomy term to be assigned with the value of the input_type. So the taxonomy (input) will also be either collection, product, or variant)

I presented this on stack exchange, and someone came up with this answer, but it is not working on my site, and I don't understand why. My taxonomies are set as hierarchical.

function wpdocs_set_terms_for_post_types() {
    $posts = get_posts( array(
        'posts_per_page' => -1,
        'post_type'      => 'uc-collections',
    ) );

    if ( ! empty( $posts ) ) {
        foreach ( $posts as $post ) {
            if ( $meta = get_post_meta( $post->ID, 'input_type', true )
                && $term = get_term_by( 'slug', $meta, 'input' )
            ) {
                wp_set_post_terms( $post->ID, $term->slug, 'input' );
            }
        }
    }
}
wpdocs_set_terms_for_post_types();

Viewing all articles
Browse latest Browse all 8245

Trending Articles