• Hello,

    I want to display a custom field on the products listing page (WooCommerce), but it doesn’t appear.

    My code (functions.php) in child theme:

    // Productkatalog test
    function add__woocommerce_after_shop_loop_item( ) {	
    	echo get_post_meta($post->ID, 'wbo_literpreis', true);
    };
    add_action( 'woocommerce_after_shop_loop_item', 'add__woocommerce_after_shop_loop_item' );

    This just displays nothing

    When echoeing on the same spot, it displays the custom field (and others ofc) to be there:

    // Productkatalog test
    function add__woocommerce_after_shop_loop_item( ) {	
    	echo the_meta();
    };
    add_action( 'woocommerce_after_shop_loop_item', 'add__woocommerce_after_shop_loop_item' );

    Unfortunately I’m not that PHP experienced.
    What am I missing?

    Thanks in advance!
    Pascal

    • This topic was modified 3 years, 7 months ago by Jan Dembowski. Reason: Moved to Fixing WordPress, this is not an Developing with WordPress topic
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    $post and its properties are out of scope in your callback. You can try inserting global $post; into your callback. This isn’t guaranteed to work, it depends on the context from which the action fired.

    If that does not work, you need to get the needed ID through some other mechanism. Might it possibly be passed by the action call? Or the loop might be driven by some other global variable. For specifics of using WooCommerce action hooks, I suggest either consulting WC documentation or asking through their dedicated support forum.
    https://woocommerce.github.io/code-reference/hooks/hooks.html
    https://ww.wp.xz.cn/support/plugin/woocommerce/

    Thread Starter pk1234

    (@pk1234)

    It worked! Thank you so much!

    Would you consider this as a robust solution? Or is it possible it “breaks” under circumstances?

    Code looks like this now:

    function add__woocommerce_after_shop_loop_item( ) {	
    	$einheit = " € / L";
    	global $post;	
    	echo get_post_meta($post->ID, 'wbo_literpreis', true);
    	echo $einheit;
    };
    add_action( 'woocommerce_after_shop_loop_item', 'add__woocommerce_after_shop_loop_item' );

    The code is in functions.php and affects productboxes (productlistings, product detailspage)

    Moderator bcworkz

    (@bcworkz)

    Relying on global $post is a common technique for anything that happens within a standard WP loop. I wasn’t 100% sure Woo also used a standard loop or not. Apparently they do, or the fix wouldn’t have worked. The only reason I can imagine this breaking is if Woo deviates from the standard loop sometime in the future. Since they have been doing it since who knows when, it’s hard to imagine they’d change. Your code should be fine.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘CustomField via function not appearing’ is closed to new replies.