Skip to content
Advertisement

Combining multiple cart item permalink changes in WooCommerce

I would like to change the permalinks of my cart item using the WooCommerce framework.

I have the following:

function addCustomFieldToUrl_1($permaLink, $cart_item, $cartItemId){
                
    if ($cart_item['product_id'] == "1713" ) {
        $newPermalink = "www.google.com";
    }
    return $newPermalink;
}

function addCustomFieldToUrl_2($permaLink, $cart_item, $cartItemId){
                
    if ($cart_item['product_id'] == "2188" ) {
        $newPermalink = "www.example.com";
    }
    return $newPermalink;
}

add_filter('woocommerce_cart_item_permalink', 'addCustomFieldToUrl_1', 10, 3);
add_filter('woocommerce_order_item_permalink', 'addCustomFieldToUrl_1', 10, 3);

add_filter('woocommerce_cart_item_permalink', 'addCustomFieldToUrl_2', 10, 3);
add_filter('woocommerce_order_item_permalink', 'addCustomFieldToUrl_2', 10, 3);

However only the second cart permalink is changed using this method. If I delete it, then the first one gets changed.

How can I combine the two functions into one and expand on that (as I have multiple products where the permalinks will need to be changed?)

Advertisement

Answer

You could apply it this way

function addCustomFieldToUrl( $permalink, $cart_item, $cartItemId ) {
                
    if ($cart_item['product_id'] == 1713 ) {
        $permalink = "www.google.com";
    } elseif ($cart_item['product_id'] == 2188 ) {
        $permalink = "www.example.com";
    }

    return $permalink;
}
add_filter('woocommerce_cart_item_permalink', 'addCustomFieldToUrl', 10, 3 );
add_filter('woocommerce_order_item_permalink', 'addCustomFieldToUrl', 10, 3 );
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement