简体   繁体   中英

Related Products ACF WordPress

I am not using a WooCommerce plugin, just your normal site.

I have a page, which I need to let the user select some 'related products'.

Now, I am using ACF, and looking at using the Post_Object to allow the user to select the product.

What this needs to do, is get the product name, but also get that products image and description.

I have used this code, from the ACF site, to attempt to grab the post object title.

    <?php

$post_object = get_field('post_object');

if( $post_object ): 

    // override $post
    $post = $post_object;
    setup_postdata( $post ); 

    ?>
    <div>
        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <span>Post Object Custom Field: <?php the_field('field_name'); ?></span>
    </div>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>

But even this won't display anything?

Is there any obvious issues anyone can see?

Since you are allowing multiple selections, the get_field will return an array of post objects. So you will need to loop through that array, using the following code. This code assumes that your Post Object field is named 'related_products', and then calls the post's excerpt value, which will check the Excerpt Field first, and if not present, will generate an excerpt from The Content of the post.

    $related_products = get_field('related_products');

    if( $related_products ): ?>
            <ul>
            <?php foreach( $related_products as $post): // variable must be called $post (IMPORTANT) ?>
                    <?php setup_postdata($post); ?>
                    <li>
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            <?php the_excerpt(); ?>
                    </li>
            <?php endforeach; ?>
            </ul>
            <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM