Pawan Kumawat

Display Product ACF Value on Shop Page : WooCommerce

To display a custom field or Advanced Custom Field (ACF) value for products on the WooCommerce shop page. you can modify the woocommerce_before_shop_loop_item_title hook, follow these steps:

 

Step 1: Add Custom Field to Your Products Using ACF Ensure you have added the desired custom field to your products using Advanced Custom Fields (ACF). If you haven’t done this yet, follow the steps mentioned earlier in the previous answers.

Step 2: Modify Functions.php or Custom Plugin Add the following code to your theme’s functions.php file or create a custom plugin:

// Display ACF value before shop loop item title
function custom_display_product_acf_value_before_title()
{
    // Check if on the shop page
    if (is_shop()) {
        global $product;

        // Get the custom field value using ACF function
        $custom_field_value = get_field('custom_field_name', $product->get_id());

        // Display the custom field value
        if ($custom_field_value) {
            echo '<div class="custom-field-value">';
            echo 'Custom Field Value: ' . $custom_field_value;
            echo '</div>';
        }
    }
}
add_action('woocommerce_before_shop_loop_item_title', 'custom_display_product_acf_value_before_title');

 

Replace 'custom_field_name' with the actual name of your ACF field that you want to display for each product. The get_field() function retrieves the value of the custom field for each product on the shop page.

Step 3: Save Changes and Test Save the changes to your functions.php file or custom plugin. The ACF value will now be displayed for each product on the WooCommerce shop page, just before the product title.

This method uses the woocommerce_before_shop_loop_item_title hook to insert content before the product title in the product loop on the shop page. It’s a cleaner approach compared to modifying the archive-product.php template directly, as it allows you to keep your changes in the functions.php file or a custom plugin and avoid any potential conflicts during theme updates.

Categories

Related Blogs