php - 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?)
Answer
Solution:
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 );
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.