WooCommerce产品属性术语值在数据库中的存储位置

时间:2019-05-16 18:07:13

标签: php mysql database wordpress woocommerce

Woocommerce将许多产品属性的值存储为空字符串。

以下是_product_attributes在数据库中显示的内容的一个示例:

a:1:{s:5:"brand";a:6:{s:4:"name";s:5:"brand";s:5:"value";s:0:"";s:11:"is_taxonomy";i:1;s:8:"position";i:0;s:10:"is_visible";i:1;s:12:"is_variation";i:0;}}

我已经在wordpress的产品数据部分中正确添加了产品属性。我根本没有编辑过php代码。如何获取它以实际存储正确的产品属性值?

1 个答案:

答案 0 :(得分:0)

产品属性值未存储在wp_post_meta表中,而是存储在wp_term_relationships中。

在查看序列化数据时,也有些奇怪:所有产品属性分类法总是以pa_ 开头,例如本例:

a:1:{s:8:"pa_color";a:6:{s:4:"name";s:8:"pa_color";s:5:"value";s:0:"";s:8:"position";i:0;s:10:"is_visible";i:0;s:12:"is_variation";i:1;s:11:"is_taxonomy";i:1;}}

要从动态产品ID中获取给定brand分类法的值,可以使用:

$taxonomy = 'brand';
$terms = wp_get_post_terms( $product_id, $taxonomy );

// Loop through WP_Term objects
foreach ( $terms as $term ) {
    $term_id   = $term->term_id;
    $term_name = $term->name;
    $term_slug = $term->slug;
}

或使用WPDB类(来自动态产品ID)的SQL查询:

global $wpdb;

$taxonomy   = 'brand'; // The taxonomy
$product_id = 37; // The product ID

$terms = $wpdb->get_results( $wpdb->prepare("
    SELECT t.term_id, t.name, t.slug
    FROM {$wpdb->prefix}terms t
    INNER JOIN {$wpdb->prefix}term_taxonomy tt
        ON t.term_id = tt.term_id
    INNER JOIN {$wpdb->prefix}term_relationships tr
        ON tt.term_taxonomy_id = tr.term_taxonomy_id
    WHERE tt.taxonomy = '%s'
    AND tr.object_id = %d
", $taxonomy, $product_id ) );

// Raw output
var_dump($terms);

因此您可以看到SQL查询使用wp_termswp_term_taxonomywp_term_relationships。通过wp_term_relationships列上的object_id表查询产品ID。

相关问题