i’m currently playing around on localhost since i’m going to design an ecommerce for a client who owns a records store. I’ve installed Elementor, WooCommerce and ACF, and at first tried to use elementor custom skin to create a custom loop for my products, where i easily added the field i wanted with dynamic data. However, this turned out to be a nightmare since being a post archive i lost the sorting etc and also for some reason the add to cart button behaved weirdly (it took me to the single product page after clicking it). So i’ve ditched that custom posts archive and used the classic product archive instead, which doesn’t allow me to add anything to the product loop directly.
I tried adding this code in my functions.php file (my custom field is named vinyl_genre and it’s part of a custom field group):
add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 ); function custom_field_display_below_title(){ global $product; // Display ACF text if( $text = get_field( 'vinyl_genre', $product->get_id() ) ) { echo '<p class="archive-genre">' . $text . '</p>'; } }
But it didnt work, instead below each product title in the archive i get this warning:
Warning: : Array to string conversion in […] wp-contentthemeshello-theme-child-masterfunctions.php on line 36 Array
I’m an absolute n00b at php, but i found the above example here on stack and just changed the field name, but to no avail. Any advice?
— EDIT —
Using print_r($text)
gives an array of values (because vinyl can have multiple genres)
Advertisement
Answer
That means that your custom field value is an array with multiple values.
Instead use the following:
add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 ); function custom_field_display_below_title(){ global $product; $values = (array) get_field( 'vinyl_genre', $product->get_id() ); // Get custom field values // Display custom field values if( ! empty($values) ) { echo '<p class="archive-genre">' . implode( ', ', $values ) . '</p>'; } }
Code goes in functions.php file of the active child theme (or active theme). It should work.