To add a new button to the WooCommerce single product page that leads to the order details page for the current product, you can use the following steps:

  1. First, create a custom function to add the button to the product page. You can do this by adding the following code to your theme’s functions.php file or to a custom plugin:
function add_order_details_button() {
   global $product;

   $order_id = get_order_id_for_product( $product->get_id() );

   if ( ! $order_id ) {
      return;
   }

   $order_url = get_edit_post_link( $order_id );

   printf(
      '<a href="%s" class="button">%s</a>',
      esc_url( $order_url ),
      esc_html__( 'View Order Details', 'your-text-domain' )
   );
}

This function will check if the current product has been purchased and, if it has, will add a button linking to the order details page for the corresponding order.

  1. Next, you need to add the button to the product page. You can do this by using the woocommerce_single_product_summary action hook:
add_action( 'woocommerce_single_product_summary', 'add_order_details_button', 25 );

This will add the button to the product page below the add to cart button.

  1. Finally, you need to define the get_order_id_for_product() function that is used in the add_order_details_button() function. This function should return the ID of the order that contains the current product. Here is an example of how you can implement this function:
function get_order_id_for_product( $product_id ) {
   $args = array(
      'numberposts' => 1,
      'post_type'   => 'shop_order',
      'meta_key'    => '_product_id',
      'meta_value'  => $product_id,
   );

   $orders = get_posts( $args );

   if ( empty( $orders ) ) {
      return false;
   }

   return $orders[0]->ID;
}

This function uses the get_posts() function to retrieve the order that contains the current product.

(Visited 53 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window