Where is WooCommerce product attribute key and val

2019-08-20 03:23发布

问题:

I added a product attribute key and value to a product.

I want to query products by this attribute. I have a query for that (not relevant here), but it returns nothing. So I popped open PHPMyAdmin and started searching my local database to start from the beginning.

I cannot find my new attribute anywhere.

So: my-attribute = "Test Value" set via the admin of my localhost version of the site. Checked the DB connection, is pointing to local MySQL instance. Saved attributes, clicked update on product, left product page and came back to ensure the attribute is indeed on the product and saved.

Nothing in the database.

Searching for my-attribute or pa_my-attribute in the wp_term_taxonomy table taxonomy column yields zero results. I do see other records here with pa_ + some other custom attribute name.

Clicking through the other tables like wp_terms or wp_woocommerce_attribute_taxonomies also doesn't show any records matching the my-attribute or qa_my-attribute input.

Added the same exact attribute to a second product and still cannot find anything. Reconfirmed DB connection. No record in database that I can find.

But it's absolutely there on the products in the admin.

What am I missing?

回答1:

Turns out they're stored in a serialized field.

$attribute_name  = 'my-attribute';
$attribute_value = 'cupcakes';

$serialized_value = serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ); 
$args = array(
    'post_type'      => 'product',
    'post_status'    => 'any',
    'posts_per_page' => -1,
    'orderby'        => 'title',
    'order'          => 'ASC',
    'meta_query' => array(
        array(
            'key'     => '_product_attributes',
            'value'   => $serialized_value,
            'compare' => 'LIKE',
        ),
    ),
);

$query = new WP_Query( $args );
$products = $query->get_posts();
//neat little array of product objects (not the full product object, 
//just data that came from query. Can use wordpress loop on $query or
//wc_get_product(--pass product ID here--)