NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Woocommerce: Creating a Shortcode with Product Link
Easy
Web Hosting Canada

Last modified : Oct 01 2022

Estimated reading time : 1 minute, 11 seconds - 98 words

With this tutorial, we will create a function that will generate a shortcode which includes a product link with its ID. These magical little shortcodes can be used strategically on your website for product placement in various spots such as the sidebar.

First we need to know the ID of our product; it can be obtained when consulting our products.

We’ll name our shortcode produrl. You can name it whatever you want obviously.

////////////////////// Shortcode product url destination /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
add_shortcode( 'produrl', 'themespress_product_url' );
function themespress_product_url($atts){
global $wpdb;
 
if ( empty( $atts ) ) {
return '';
}
 
if ( isset( $atts['id'] ) ) {
$product_data = get_post( $atts['id'] );
} 
else {
return '';
}
 
if ( 'product' !== $product_data->post_type ) {
return '';
}
 
$_product = wc_get_product( $product_data );
$url = esc_url( get_post_permalink($_product->id) );
return '<a class="more" href="'. $url . '">T&eacute;l&eacute;charger</a>';
}

So here’s the shortcode you can use anywhere on your website; simply replace the product ID with the ID you want to display.

[produrl id="2254"]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>