Support

Account

Home Forums Front-end Issues acf inside functions.php

Solved

acf inside functions.php

  • I am trying to show an ACF custom field inside woocommerce loop.

    #woocommerce expires
    add_action( 'woocommerce_after_shop_loop_item_title' , 'woocommerce_product_expire', 10 );
    /**
     * woocommerce_expires
     *
    */
    function woocommerce_product_expire() {
        
    #Call the post expirator acf field
    echo ( ' <p><?php if( get_field('expires') ): ?>			
    			<p>expires: </p>
    			<?php the_field('expires'); ?>
    				<?php endif; ?></p>' );
        
    }

    Any solution?

  • Hi @pansotdev

    There are some syntax issues in your code.

    First, you can’t use “#” for the comment. Kindly use “//” instead.

    Second, echo is used only to print text, not the code like in your example.

    Third, it’s possible that the function is executed outside of WordPress loop. In this case, you need to pass the product ID to the second get_field() parameter. So your code should be like this:

    function woocommerce_product_expire() {
    
    // get the current post in the loop
    global $post;
    
    //Call the post expirator acf field
    ?>
    
        <p>
            <?php if( get_field('expires', $post->ID) ): ?>            
                <p>expires: </p>
                <?php the_field('expires', $post->ID); ?>
            <?php endif; ?>
        </p>
    
    <?php
    }

    I hope this makes sense 🙂

  • Thank you for your answer @acf-support. It works great 🙂

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

The topic ‘acf inside functions.php’ is closed to new replies.