Add button linked to single product page on order detail page

I have write a code on functions.php so when customers click a button on order detail page, redirected to product page and review tab of the product they bought. But as a novice coder, I can’t get the full link to the product page and the review tab. The code below if clicked is only going to http://mywebsite.com/shop/

add_action('woocommerce_order_details_after_order_table', 'tl_review_for_order');
function tl_review_for_order() { ?>
<a class="button-3" href="<?php echo get_permalink( wc_get_page_id( 'shop' ) ) ; ?>"><?php _e( 'REVIEW', 'woocommerce' ) ?></a>
<?php
}

So what I need is when the button clicked should go to the full link of the product page + review like http://mywebsite.com/shop/product-name/#tab-reviews

any one could solve this? Thanks

Answer

The woocommerce_order_details_after_order_table hook receives the WC_Order object as the $order argument. This means you can get the items from the order with $order->get_items().

That will return an Array of WC_Order_Items. From this you can get the associated product of the first item, which you can use to get its permalink, to which you can append #tab-reviews:

function tl_review_for_order( $order ) {
    // Get the order items.
    $order_items = $order->get_items();

    // Get the first or only order item.
    $order_item = reset( $order_items );

    // Get the product object from the order item.
    $product = $order_item->get_product();

    // Make sure the product still exists.
    if ( $product ) {
        // Output link using WooCommerce function for getting a product's link.
        printf(
            '<a class="button-3" href="%1$s#tab-reviews">%2$s</a>',
            esc_url( $product->get_permalink() ),
            __( 'Review', 'woocommerce' )
        ); 
    }
}
add_action( 'woocommerce_order_details_after_order_table', 'tl_review_for_order' );

Note that I used $product->get_permalink() to get the URL, and not just get_permalink(). This is to maintain forwards compatibility for when WooCommerce products are no longer stored as posts. Something that is not far off.

Attribution
Source : Link , Question Author : jasaweb , Answer Author : Jacob Peattie

Leave a Comment