Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active November 12, 2023 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braddalton/2489501a6627cd429c7f108e152b64f7 to your computer and use it in GitHub Desktop.
Save braddalton/2489501a6627cd429c7f108e152b64f7 to your computer and use it in GitHub Desktop.
Shortcode to add custom fields to the product description https://wpsites.net/?p=114180
// Add custom field to product general settings metabox
function custom_product_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Custom field
woocommerce_wp_textarea_input(
array(
'id' => '_custom_product_description',
'label' => __('Custom Product Description', 'your-textdomain'),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __('Enter a custom description for the product.', 'your-textdomain')
)
);
echo '</div>';
}
add_action('woocommerce_product_options_general_product_data', 'custom_product_general_fields');
// Save custom field value
function save_custom_product_general_fields($post_id) {
$custom_description = isset($_POST['_custom_product_description']) ? $_POST['_custom_product_description'] : '';
update_post_meta($post_id, '_custom_product_description', sanitize_text_field($custom_description));
}
add_action('woocommerce_process_product_meta', 'save_custom_product_general_fields');
// Define the shortcode function
function custom_product_description_shortcode() {
global $product;
// Get the custom field value
$custom_description = get_post_meta($product->get_id(), '_custom_product_description', true);
// Output the custom field value
if (!empty($custom_description)) {
return '<div class="custom-product-description">' . wpautop($custom_description) . '</div>';
}
return ''; // Return empty string if the custom field is not set
}
add_shortcode('custom_product_description', 'custom_product_description_shortcode');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment