NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Oct 01 2022
Estimated reading time : 1 minute, 11 seconds - 98 words
Share the post "Woocommerce: Creating a Shortcode with Product Link"
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élé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"]