phpwordpress

Show A Custom Field from Similar Category (Getting A Custom Field from Similar Posts)


I have a single.php where I display a Product. I have Category and Sub Categories for this product and I want to display a the bottom a custom field image from similar categories.

For Example I'm in Red Bag 1, I want to put in the bottom a thumbnail of similar pages like Red Bag 2 and Red Bag 3 which are in the same category "Red Bag"

I actually have a code already but I don't know how to target the custom field created by Advance Custom Field plugin: the_field("product_image")

here's my code:

              <?php
            global $post;
            $cat_ID=array();
            $categories = get_the_category(); //get all categories for this post
              foreach($categories as $category) {
                array_push($cat_ID,$category->cat_ID);
              }
              $args = array(
              'orderby' => 'date',
              'order' => 'DESC',
              'post_type' => 'post',
              'numberposts' => 8,
              'post__not_in' => array($post->ID),
              'category__in' => $cat_ID
              ); // post__not_in will exclude the post we are displaying
                $cat_posts = get_posts($args);
                $out='';


                  foreach($cat_posts as $cat_post) {
                      $out .= '<li>';
                      $out .=  '<a href="'.get_permalink($cat_post->ID).'" title="'.wptexturize($cat_post->post_title).'">'.wptexturize($cat_post->post_title).'</a></li>';
                  }
                $out = '<ul class="cat_post">' . $out . '</ul>';
                echo $out;
            ?>

where .wptexturize($cat_post->post_title). suppose to be an image instead of the title. The image source should be taken from the custom field the_field("product_image")


Solution

  • If you would use post_thumbnail_html it would be a lot simpeler. Instead you use a a function which is not default to wordpress: the_field.
    I don't know which plugin does this.

    Probably that function (the_field) would work within a normal loop.
    To do that you should change get_posts($args) to WP_Query($args) and replace the foreach($cat_posts.. with a loop.

    I advise to use the default wordpress thumbnail/featured image with post_thumbnail_html