Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active July 15, 2024 10:46
Show Gist options
  • Save braddalton/2576059516e8bcfbeccc6626b9287672 to your computer and use it in GitHub Desktop.
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/
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