根据产品ID添加不同的链接

时间:2018-07-28 04:10:27

标签: php wordpress woocommerce product orders

对于woocommerce,我有以下代码,这些代码根据订单的状态在我的帐户订单列表中添加了一个链接按钮:

function sv_add_my_account_order_actions( $actions, $order ) {

// only add our button if the order is paid for
// if using WC 2.5+, can simplify this to: if ( ! $order->is_paid() )

if ( ! ( $order->has_status( 'briefing' ) ) ) {
    return $actions;
}  

$actions['briefing'] = array(
    // adjust URL as needed
    'name' => __( 'Responder Briefing', 'my-textdomain' ),
    'url'  => 'https://link1.com/order=' . $order->get_order_number(), 
);

return $actions;
}
add_filter( 'woocommerce_my_account_my_orders_actions', 'sv_add_my_account_order_actions', 10, 2 );

我希望此链接根据该订单中包含的产品ID进行更改,可以吗?

2 个答案:

答案 0 :(得分:0)

是的,有可能。在下面的示例中,您可以定位产品ID,产品ID数组或产品类别。您可以根据需要轻松地安排代码:

add_filter( 'woocommerce_my_account_my_orders_actions', 'add_my_account_order_actions', 10, 2 );
function add_my_account_order_actions( $actions, $order ) {

    if ( ! $order->has_status( 'briefing' ) ) {
        return $actions;
    }

    // Default URL
    $url = 'https://link3.com/order=' . $order->get_order_number();

    // Loop through order items and change Url depending on product ID
    foreach( $order->get_items() as $item_id =>$item ){
        // Get the product ID
        $product_ids = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();

        // For one product id
        if( $product_id == 37 ) {
            $url = 'https://link1.com/order=' . $order->get_order_number();
        } 
        // For an array of product ids
        elseif( in_array( $product_id, array(43, 57, 71, 84) ) ) {
            $url = 'https://link2.com/order=' . $order->get_order_number();
        } 
        // For product categories (term ids, slugs or names )
        elseif( has_term( array('clothing'), 'product_cat', $item->get_product_id() ) ) {
            $url = 'https://link3.com/order=' . $order->get_order_number();
        } 
    }

    $actions['briefing'] = array(
        // adjust URL as needed
        'url'  => 'https://link1.com/order=' . $order->get_order_number(), 
        'name' => __( 'Responder Briefing', 'my-textdomain' ),
    );

    return $actions;
}

代码进入活动子主题(或活动主题)的function.php文件中。经过测试并可以正常工作。

  

但是,由于您可以在订单中包含许多订单项,因此,如果您有很多条件,它将仅考虑其中一项(最后一个匹配项)。

答案 1 :(得分:0)

它不适用于我。它采用以下URL:

$ actions ['briefing'] = array (
         // adjust URL as needed
         'url' => 'https://link1.com/order='. $ order-> get_order_number (),
         'name' => __ ('Reply Briefing', 'my-textdomain'),
     );