Last active
July 15, 2024 10:46
-
-
Save braddalton/2576059516e8bcfbeccc6626b9287672 to your computer and use it in GitHub Desktop.
Add custom fields to both single and archive pages in WooCommerce https://wpsites.net/wordpress-tutorials/sub-heading-on-single-shop-page-archives-in-woocommerce/
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
add_action('woocommerce_product_options_general_product_data', 'custom_woocommerce_product_fields'); | |
function custom_woocommerce_product_fields() { | |
woocommerce_wp_text_input([ | |
'id' => '_custom_field', | |
'label' => __('Custom Field', 'woocommerce'), | |
'desc_tip' => 'true', | |
'description' => __('Enter the value for the custom field.', 'woocommerce'), | |
]); | |
} | |
add_action('woocommerce_process_product_meta', 'save_custom_woocommerce_product_fields'); | |
function save_custom_woocommerce_product_fields($post_id) { | |
$custom_field_value = isset($_POST['_custom_field']) ? sanitize_text_field($_POST['_custom_field']) : ''; | |
update_post_meta($post_id, '_custom_field', $custom_field_value); | |
} | |
add_action('woocommerce_single_product_summary', 'display_custom_field_single_product', 25); | |
function display_custom_field_single_product() { | |
global $product; | |
$custom_field_value = get_post_meta($product->get_id(), '_custom_field', true); | |
if ($custom_field_value) { | |
echo '<p class="custom-field">' . esc_html($custom_field_value) . '</p>'; | |
} | |
} | |
add_action('woocommerce_after_shop_loop_item_title', 'display_custom_field_archive_page', 15); | |
function display_custom_field_archive_page() { | |
global $product; | |
$custom_field_value = get_post_meta($product->get_id(), '_custom_field', true); | |
if ($custom_field_value) { | |
echo '<p class="custom-field">' . esc_html($custom_field_value) . '</p>'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment