user8205257
user8205257

Reputation:

Unable to return 'attribute' data in Woocomerce

pa_I am trying to dog into products' attribute data in order to compare the attribute between items in the cart. However, I cannot access the data. The following code returns the following on the var_dump command:

C:\wamp\www\wizstaginglocal\wp-content\plugins\code-snippets\php\snippet-ops.php(426) : eval()'d code:17:boolean false

In other words nothing

Code:

add_action('woocommerce_before_cart', 'wiz_scale_woocommerce_before_cart');

function wiz_scale_woocommerce_before_cart() {
    foreach(WC() -> cart -> get_cart() as $cart_item_key => $cart_item) {
        // HERE the WC_Product object
        $product = $cart_item['data'];
        echo "My Product ID is {$cart_item['product_id']} \n";

        $attributes = $product -> get_attributes();
        foreach($attributes as $taxonomy => $value) {
            // The WP_Term object
            $term_obj = get_term_by('pa_1_scale', $value, $taxonomy);
            $term_name = $term_obj -> name;

        }
        echo '<pre>';
        var_dump($term_obj);
        echo '</pre>';
    }
}

At var_dump for the $attributes shows, for the relevant slug:

array (size=3).... 'pa_1_scale' => object(WC_Product_Attribute)[1383] protected 'data' => array (size=6) 'id' => int 1 'name' => string 'pa_1_scale' (length=10) 'options' => array (size=1) ... 'position' => int 2 'visible' => boolean true 'variation' => boolean false

I also became aware of this post: is this the reason?

Upvotes: 0

Views: 127

Answers (1)

user8205257
user8205257

Reputation:

The attribute data in is serialized, I cannot find a way to extract it. The work around which was successful was to write an SQL query to the WP database.

function mycustomfunc_retrieve_attribute_for product() {
foreach(WC() -> cart -> get_cart() as $cart_item_key => $cart_item) {
    $product = $cart_item['product_id'];   
// perform wpdb search
global $wpdb;
$myatt = $wpdb->get_var(
    $wpdb->prepare(
    "SELECT DISTINCT
    t.name AS 'Term Name'
    FROM
    wiz_posts AS p
    INNER JOIN
    wiz_term_relationships AS tr ON p.id = tr.object_id
    INNER JOIN
    wiz_term_taxonomy AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
    INNER JOIN
    wiz_terms AS t ON t.term_id = tt.term_id
    WHERE
    p.post_type = 'product'
    AND
    p.ID = %d
    AND
    tt.taxonomy = 'mySlugName'
    ",
    $product
    )
    );

 echo "My Product ID is {$product} and the attribute is {$myatt} \n";
 }

Upvotes: 0

Related Questions