Attaching post objects from other posts with ACF


Hello,

I'm trying to get the content and meta (ACF) from one post and attach it to another post. It is a review site with each reviewed product being a seperate post for SEO purposes. However when creating the ACF-fields and trying to implement in the single view of Beans I'm running into a slight problem.

Where can I fire my custom code to make sure that it comes after wp_reset_postdata for the main content loop? When I fire my function in beans_content_after_markup the template hooks (i.e. the_title(), the_permalink()) shows the data from the parent post.

Here is my code to fetch and print the products

//Get products from ACF
add_action( 'beans_content_after_markup', 'beans_child_show_products' );
function beans_child_show_products() {
    ?>
    <?php $post_objects = get_field( 'attach_products' ); ?>
  <?php if ( $post_objects ): ?>
    <?php foreach ( $post_objects as $post ):  ?>
     <?php setup_postdata( $post ); ?>
     <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
   <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>
  <?php endif; ?>
    <?php
}

A small update if it helps. I changed the field to Relationship field type but I still have the same issue. Also I'm now firing my function in beans_after_posts_loop but still I would get the data from the current post only. I looked around on the ACF forums and I found this bit of debugging code:

//Get products from ACF
add_action( 'beans_after_posts_loop', 'beans_child_show_products' );
function beans_child_show_products() {
    ?>

    <?php if ( have_posts() ) : ?>
      <?php /* Start the Loop */ ?>
     <?php while (have_posts()) : the_post(); ?>

       <h2><?php the_title(); ?></h2>

        <?php
       $posts = get_field('attach_products');

        echo '<pre>';
         print_r( $posts );
        echo '</pre>';

        ?>

      <?php endwhile; ?>
    <?php endif; ?>

    <?php
}

This actually prints the data from my attached posts.


Hi Olaf,

Are you trying to get the field from another post on the blog index view or single post view?

If you want to get the value of a post which isn't the current post your are viewing, then you need to pass its post ID as a second argument of the ACD get_field() function. For example, if you are looking to get the value of the post ID 63 and you are viewing the post 52, you need to do get_field( 'attach_products', 63 ) which will work whether you are in or out of the loop.

Thanks,

Write a reply

Login or register to write a reply, it's free!