简体   繁体   中英

Wordpress Advanced Custom Fields display two fields from two different post types in one template

I have two post types. I need to display content from each within the same loop. At the moment, I can call the 'releases' post type to display content, but I also need to call the 'artists' post type to display some content in the same DIV.

The below line breaks the page with a 'Catchable fatal error: Object of class WP_Post could not be converted to string error'.

<?php the_field('release_artist_name'); ?>

How do I get the release_artist_name field to stop breaking the site? It is a field via a Post Object (post type is named 'artists'). Any help appreciated.

    <?php 
       $posts = get_posts(array(
        'post_type'     => 'releases'
    )
       ));

       if( $posts ): ?>
    <?php foreach( $posts as $post ): 
       setup_postdata( $post )       
       ?>
<div>
    <?php the_title(); ?> // THIS COMES FROM RELEASES POST TYPE
    <?php the_field('release_artist_name'); ?> // THIS SHOULD COME FROM ARTISTS POST TYPE BUT BREAKS THE PAGE
</div>

    <?php endif; ?>
    <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>

As asked for below, results from the print_r($posts)...

Array ( [0] => WP_Post Object ( [ID] => 10661 [post_author] => 1 [post_date] => 2016-03-31 02:37:57 [post_date_gmt] => 2016-03-31 02:37:57 [post_content] => [post_title] => New Gold Mountain [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => new-gold-mountain [to_ping] => [pinged] => [post_modified] => 2016-03-31 04:41:04 [post_modified_gmt] => 2016-03-31 04:41:04 [post_content_filtered] => [post_parent] => 0 [guid] => http://127.0.0.1:4001/wordpress/?post_type=releases&p=10661 [menu_order] => 0 [post_type] => releases [post_mime_type] => [comment_count] => 0 [filter] => raw )

If you have a post type for artists and you're using ACF, in your releases post type you should add a custom field named release_artist (for example) of type Post Object where you'll associate the Artist (or Artists) for a Release. I recommend you to set this field to return Post ID instead of Post Object .

Then in your loop, you get the artist ID:

$artist_id = get_field('release_artist');

So you can use this ID to query any custom field of the artist:

$artist_name = get_field('artist_name', $artist_id);

Note that all ACF functions accept a second parameter with a post ID to query other posts when, for example, you're inside the loop.

See get_field Documentation. Hope this helps.

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