Last active
September 14, 2023 04:43
-
-
Save jasperf/2154e63c33087cbb14999a36536a4375 to your computer and use it in GitHub Desktop.
Create button shortcode with link containing WooCommerce product slug or product title. Slug used by default here
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function dynamic_product_link_button_shortcode($atts) { | |
// Parse attributes | |
$atts = shortcode_atts(array( | |
'text' => 'Fitting & Maat', // Default button text | |
), $atts); | |
// Check if WooCommerce is active and a product is available | |
if (class_exists('WooCommerce') && is_product()) { | |
// Get the current product ID | |
$product_id = get_the_ID(); | |
// Check if $product_id is not null | |
if ($product_id) { | |
// Get the product slug | |
$product_slug = get_post_field('post_name', $product_id); | |
// Generate dynamic link with product title | |
// $dynamic_link = home_url('/custom-page/' . sanitize_title(get_the_title($product_id))) . '.pdf'; | |
// Generate the dynamic hyperlink with product slug | |
$dynamic_link = home_url('/wp-content/uploads/sizes/' . sanitize_title($product_slug)) . '.pdf'; | |
// Output the dynamic link as a button | |
return '<a href="' . esc_url($dynamic_link) . '" class="button" target="_blank">' . esc_html($atts['text']) . '</a>'; | |
} | |
} | |
// If no product is available, return a message or an empty string | |
return ''; // You can customize this part as needed | |
} | |
add_shortcode('dynamic_product_link_button', 'dynamic_product_link_button_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment