skip to Main Content

I have this WP_Query:

$query = new WP_Query(
        array(
            'posts_per_page' => $postsCount,
            'post_type' => 'events',
            'taxonomy' => 'events-category',
            'meta_key' => 'event-start-date',
            'orderby' => $postsOrderBy,
            'order' => $postsOrder,
            'meta_query' => array(
                array(
                        'key' => 'event-start-date',
                        'compare' => '>=',
                        'value' => date("Y-m-d"),
                        'type' => 'DATE',
                ),
            ),
        ),
    );
if ($query->have_posts()):
    while ($query->have_posts()): $query->the_post();
        // content
    endwhile;
    wp_reset_query();
endif;

In ‘content’ I have something like this:

    <?php
    $post_object = get_field('event-ticket');
        if( $post_object ):
            $post = $post_object;
            setup_postdata( $post );
            $product->get_id(); ?>

    <div class="e-post__details-item e-post__details-item--event-price"><i class="e-post__details-item--icon fas fa-ticket-alt"></i><?php woocommerce_get_template( 'single-product/price.php' ); ?></div>

    <div class="l-cta l-cta--events">

    <div class="e-post__event-stock-status">
        <?php if ( $product->is_in_stock() ) {
        echo '<div class="e-post__event-stock-status-available">'.__('Dostępne!', 'woocommerce').'</div>';
        } elseif ( ! $product->is_in_stock() ) {
        echo '<div class="e-post__event-stock-status-unavailable">'.__('Wyprzedane!', 'woocommerce').'</div>';
        } ?>
    </div>

    </div>

    <?php
    wp_reset_postdata();
    endif;
    ?>

get_field(‘event-ticket’) is ACF post object field type with ‘Post Object’ return object. This field pointing on WooCommerce product to get price and quantity stock.

WP_Query is loop of the CPT ‘Events’. In every event I’m using post object field to point to the WooCommerce product, which is a ticket.

PROBLEM:
Datas from ‘event-ticket’ works on every subpages (archives, taxonomy, pages, cpt posts) but not on front (home) page:

Uncaught Error
: Call to a member function get_id() on null

What could be the reason?

2

Answers


  1. Chosen as BEST ANSWER

    I figure out: I just add global $product; before $product->get_id(); and now it's working :)


  2. You have not declared $product before. This is why you get this error. $product->get_id(); when you did not initialized $product earlier.

    Maybe you want first:

    $product = new WC_Product($post->ID);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search