0

I am trying to add the permalink of product on woocommerce admin order page with this code:

function fpd_custom_order_item_values($_product) {

$url = $_product->permalink;

echo '<p>'.$url.'</p>';
}
add_action( 'woocommerce_before_order_itemmeta', 'fpd_custom_order_item_values', 100, 1);

However, this does not output the product permalink. When I replace $url = $_product->permalink; with $url = $_product->name;, the name gets echoed. What am I doing wrong here?

2 Answers 2

1

There's no permalink property of a product. Permalinks are not stored in the database, because they're generated based on a number of external factors. Therefore you need to use a function to retrieve the permalink. In WooCommerce the best way to do this is with:

function fpd_custom_order_item_values($_product) {
    $url = $_product->get_permalink();

    echo '<p>' . esc_url( $url ) . '</p>';
}
add_action( 'woocommerce_before_order_itemmeta', 'fpd_custom_order_item_values', 100, 1);

Also, make sure you're escaping your output. Since this is a URL, use esc_url().

1
  • This is working fine for orders with products but if an order contains products + flat rate shipping (which does not have a permalink), there's an error as shipping charge doesn't have any permalink. How to solve this?
    – dc09
    Jun 18, 2019 at 16:22
0
function fpd_custom_order_item_values($item_id, $item, $product) {
    $url = get_permalink($product->get_id());
    echo '<p>'.$url.'</p>';}

add_action('woocommerce_order_item_meta_end', 'fpd_custom_order_item_values', 10, 3);

The function name is changed to fpd_custom_order_item_values to match the function you specified in your question.

The function now takes three arguments: $item_id, $item, and $product. These variables are used to get the product ID and retrieve the permalink for the product.

The $url variable is set using the get_permalink() function, which takes the product ID as an argument.

The add_action() hook is changed to woocommerce_order_item_meta_end to ensure that the permalink is displayed at the end of the order item meta data.

By making these modifications, you should be able to display the product permalink on the WooCommerce admin order page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.