Home > Back-end >  Advanced Custom Field - Extract multiple value of Relationship field
Advanced Custom Field - Extract multiple value of Relationship field

Time:03-15

I'm using the "Adavanced Custom Field" WordPress plugin for the creation of relational fields. I created a custom post type "CPT 1" and added it as a relational field in the user card. The goal is to assign one or more CPT 1 terms to users.Inside the archive page of the custom post type I want to show the terms of the relational field of the current user.

I can't extract the terms within an archive page. I need it inside an archive page and in other page templates, as I have to perform a series of checks (IF in PHP).

The code I used is the following:

$user_id = get_the_author_meta('ID');
$custom_field = get_field_object('custom_field_client', 'user_'. $user_id );

echo $custom_field;

I should extract an array of values. How can I solve? Thank you

CodePudding user response:

Have you checked the docs?

There is an example that could work:

<?php
$featured_posts = get_field('custom_field_client', 'user_'. $user_id );
if( $featured_posts ): ?>
    <ul>
    <?php foreach( $featured_posts as $post ): 

        // Setup this post for WP functions (variable must be named $post).
        setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <span>A custom field from this post: <?php the_field( 'field_name' ); ?></span>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php 
    // Reset the global post object so that the rest of the page works correctly.
    wp_reset_postdata(); ?>
<?php endif; ?>

CodePudding user response:

all works fine. I have two custom post types: "book" and "product sector". When I add a new book, I assign it a product sector (via a relational field). I need to create a loop within which to show only the books of some product sectors.

I followed this documentation to write this code, but it doesn't work:

<?php 

$args = array(
    'numberposts'   => -1,
    'post_type'     => 'book',
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'book',
            'value'     => array('mod_1', 'mod_24'),
            'compare'   => '='
        ),
        array(
            'key'       => 'commodity_sector',
            'value'     => array('industrial', 'technology'),
            'compare'   => '='
        )
    )
);


// query
$the_query = new WP_Query( $args );

?>
<?php if( $the_query->have_posts() ): ?>
    <ul>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?>
            </a>
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

The code doesn't display anything, where is the error? Thank you, Roberto

  • Related