PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] How can I set 'product_cat' terms from wp_postmeta values?

 August 26, 2022     php, woocommerce, wordpress     No comments   

Issue

I'm looking to have our woocommerce site display some data that I would like my clients to be able to set through their POS and inventory management software for ease of access.

This data will be stored in the wp_postmeta table.

I'm trying to write a function that will append the value from get_the_meta($id, custom-meta, true) to the 'product_cat' taxonomy.

I've played with a few iterations and have not been able to figure things out.

Here is the most recent function that is not working for me, but also not breaking things.

function lf_use_meta_as_product_cat() {
    $id = get_the_ID();
    $strain_controller = get_post_meta( $id, 'show strain', true );
    if ( strpos( $strain_controller, 'true') !== false ) {
        $strain = get_post_meta( $id, 'strain', true );
        if ( ! has_term( $strain, 'product_cat', $id ) ) {
            wp_set_object_terms( $id, $strain, 'product_cat', true );
        }
    }
}

add_action( 'wp_loaded', 'lf_use_meta_as_product_cat', 10 );

The variable I've grabbed with $strain_controller will either be "true" or "false".

I do have a product in the database that has the required post meta, and I know that I can pull and display the meta like such as I have working functions that do so, but I'm not winning.


Solution

Thanks to CBroe for making excellent suggestions, prompting me to figure this out myself.

Here is the code ->

function lf_use_meta_as_product_tag() {
    $id = get_the_ID();
    $strain_controller = get_post_meta( $id, 'show strain', true );
    if ( strpos( $strain_controller, 'true') !== false ) {
        
        $strain = get_post_meta( $id, 'strain', true );
        
        if ( ! has_term( $strain, 'product_tag', $id ) ) {
            wp_set_object_terms( $id, $strain, 'product_tag', true );
        }
    }
}

add_action( 'woocommerce_new_product', 'lf_use_meta_as_product_tag', 10 );
add_action( 'woocommerce_update_product', 'lf_use_meta_as_product_tag', 10);


Answered By - lforsey
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing