Display html for selected products or products categories

Viewed 266

Hello I am using advanced custom field plugin for displaying some html only for selected products or only for products for selected categories in option page with relationship picker. My result instead is displaying for all products. This is what I have:

$products = get_field('products_picker', 'option');
$categories =  get_field('categories_picker', 'option');
$prom_img = get_field('prom_img', 'option');


if ( $products ) {

 foreach( $products as $p ):
 
       if( $post->ID == $p->ID ):

  <img src="<?php echo  $prom_img['url']; ?>">


    endif;
 endforeach;
  }

 if ( $categories ) {

 foreach( $categories as $term ):
 
       $category = get_term( $term );
    
   if( has_term( $category, 'product_cat', $post )) {
      ?>

 <img src="<?php echo  $prom_img['url']; ?>">

    endif;
 endforeach;
  }

2 Answers

In similar cases I create a new wp_query passing the array with the post IDs like below:

 $posts = get_field('products_picker', 'option');
 $new_query = new WP_Query(array(
  'post_type'     => array('post'),
  'post__in'      => $posts,
  'orderby'       => 'post__in',
 ));

if ( $new_query->have_posts() ) :
while ( $new_query->have_posts() ) : $new_query->the_post();

//your code here

endwhile;
endif;

For the categories part you can use a query like this:

  $categories =  get_field('categories_picker', 'option');
  $args = array(
      'post_type' => 'post',
      'tax_query' => array(
          array(
              'taxonomy' => 'category',
              'field' => 'term_id',
              'terms' => $categories[0]
          )
       )
  );
  $cat_query = new WP_Query($args);

I've not tested this in Wordpress, but the first thing I would try is to rename the $post variable that pulls the ACF field to '$posts' (plural).

Then change the foreach loop as follows.

$posts = get_field('products_picker', 'option');
$prom_img = get_field('prom_img', 'option');


if ( $posts ) {

 foreach( $posts as $post ):

  setup_postdata($post);
   
$sales_html = '<div class="promo-badge test"><img src=' . $prom_img['url'] . '></div>';

  wp_reset_postdata();
 endforeach;
  }

That might fix it... I'm not sure you won't need to turn the foreach loop into an actual Wordpress style loop (the type with while(have_posts()): the_post(); etc. like in @kaize answer below)

See here if my solution didn't help: https://www.advancedcustomfields.com/resources/querying-relationship-fields/

Related