Support

Account

Home Forums Front-end Issues get_field() returns null

Solving

get_field() returns null

  • Im making a custom shortcode that returns products as html, i was trying to add a acf field to display on each of the products, when i try to use get field on each of my products it returns null

  • also for some really odd reason some times it displays on few products, some times displays on all of them but for the past few hours it is not displaying on any of them

    add_shortcode( 'ek_prod', 'ran_fun' );
    function ran_fun($atts) {
        $atts = shortcode_atts($default, $atts); 
        ob_start();
        ?>
    
        <div>
            <ul class="ek-grid">
                <?php   
                    $args = array(
                        'limit' => 5,
                        'order' => 'DESC',
                        'post_type' => 'products',
                        'status' => 'publish',
                        'orderby' => 'rand',
                    );
                    $products = wc_get_products( $args );
                    if ($products) {
                        foreach ($products as $product ) {
                            $permalink = get_permalink(get_the_id($product));
                ?>
                    <li class="ek-li">
                        <a href="<?php echo $product->get_permalink() ?>">
                            <img src="<?php echo wp_get_attachment_url( $product->get_image_id() )?>" alt="">
                            <h2><?php echo $product->get_title()?></h2>
                            <h3><?php echo get_field("platform", $product->get_id())?></h3>
                            <h4><?php echo get_field("region", $product->get_id())?></h4>
                            
                            <bdi><span>$</span><?php echo $product->get_price()?></bdi>
                        </a>
                    </li>
                <?php
                        }
                    }
                ?>
            </ul>
        </div>
    
        <?php
    
        return ob_get_clean();
    }
  • Looking at this example https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/

    The function wc_get_products() returns an object and the products are located in a the “products” property of that object. See the loop in the example were they reference $featured_products->products. I don’t know if this is right or not, you need to look into the WC documentation. I’m guessing that it’s not working correctly because you may not be looping correctly but that is just a guess. I’m not an expert on WC.

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

You must be logged in to reply to this topic.