woocommerce将variant-id更改为产品属性名称

时间:2020-04-07 18:00:01

标签: php wordpress woocommerce hook hook-woocommerce

我想通过使用产品属性的名称而不是id变体来重建代码。

通过此代码:

function action_woocommerce_thankyou( $order_id ) {
    // Get $order object
    $order = wc_get_order( $order_id );

    // Get items
    $items = $order->get_items();

    // Set variable
    $found = false;

    // Set variable
    $output = '';

    // Loop
    foreach ( $items as $item ) {
        // Add whatever variation id you want below here.
        if ( isset( $item[ 'variation_id' ] ) && $item[ 'variation_id' ] == 9647 ) {
            $output = 'Thank you for buy VARIABLE A-9647';
            $found = true;
            break;
        }

        if ( isset( $item[ 'variation_id' ] ) && $item[ 'variation_id' ] == 9648 ) {
            $output = 'Thank you for buy VARIABLE B-9648';
            $found = true;
            break;
        }
    }

    // Get payment method
    $payment_method = $order->get_payment_method();

    // Payment method = basc & found = true
    if ( $payment_method == 'bacs' && $found ) {
        $output .= ' YOUR PAYMENT IS BACS';
    }

    // Print result
    echo $output;
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );

我想通过使用产品属性的名称而不是id变体来重构代码

如何更改此代码

来自

variation_id

product name attribute

更确切地说,这些行:

if ( isset( $item[ 'variation_id' ] ) && $item[ 'variation_id' ] == 9647 )

if ( isset( $item[ 'variation_id' ] ) && $item[ 'variation_id' ] == 9648 )

谢谢!

1 个答案:

答案 0 :(得分:1)

假设您是这个意思吗?

function action_woocommerce_thankyou( $order_id ) {
    // Get $order object
    $order = wc_get_order( $order_id );

    // Get items
    $items = $order->get_items();

    // Set variable
    $found = false;

    // Set variable
    $output = '';

    // Loop
    foreach ( $items as $item ) {
        // The WC_Product object
        $product = $item->get_product();

        // Add whatever attribute you want below here.
        if ( !empty( $product->get_attribute( 'pa_kleur' ) ) ) {
            $output = 'Thank you...1';
            $found = true;
            break;
        }

        if ( !empty( $product->get_attribute( 'pa_jaar' ) ) ) {
            $output = 'Thank you...2';
            $found = true;
            break;
        }
    }

    // Get payment method
    $payment_method = $order->get_payment_method();

    // Payment method = basc & found = true
    if ( $payment_method == 'bacs' && $found ) {
        $output .= ' YOUR PAYMENT IS BACS';
    }

    // Print result
    echo $output;
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );