Home > Mobile >  Display WooCommerce product SKU in foreach loop (ACF relationship field)
Display WooCommerce product SKU in foreach loop (ACF relationship field)

Time:04-28

I'm working with an ACF relationship field in order to display specific woocommerce products on a single custom post type page. Below code is working fine but I also would like to echo the product SKU and can't figure it out. Below is my current code:

<?php $posts = get_field('linked_realisaties');
if( $posts ): ?>
<?php foreach( $posts as $p): ?>
    <a href="<?php echo get_permalink( $p->ID ); ?>">
        <?php 
          echo get_the_post_thumbnail( $p->ID, 'thumbnail' )
                ?>
            <div style="overflow:hidden">
                <span><?php the_field('linked_product_1_qty'); ?>x <?php echo $p->post_title; ?></span>
            </div>
            </a>
<?php endforeach; ?>
<?php endif; ?>

CodePudding user response:

<?php $posts = get_field('linked_realisaties');
    if ($posts):
        ?>
            <?php foreach ($posts as $p):
                
            $product = wc_get_product($p->ID);
            $product_perma_link = $product->get_permalink();
            $sku = $product->get_sku();
            $product_name = $product->get_name();
                
                ?>
            <a href="<?php echo $product_perma_link ?>">
                <?php
                echo get_the_post_thumbnail($p->ID, 'thumbnail')
                ?>
                <div style="overflow:hidden">
                    <span><?php the_field('linked_product_1_qty'); ?>x <?php echo $product_name ?></span>
                </div>
            </a>
        <?php endforeach; ?>
<?php endif; ?>
  • Related