Home Forums Front-end Issues Relationship returns array of string instead of post object


Relationship returns array of string instead of post object

  • Hey guys!
    Thanks for taking a look.
    Have looked around but can’t find an answer…

    Here is my code:

    function relation_product() {
    	global $post;	
    	$product = wc_get_product( $post->ID );// Check for the custom field value
    	$title = $product->get_meta( 'prenomnom_auteur1' );// on récupère l'ID du post Auteur
    	if( $title ) {// Only display our field if we've got a value for the field title
    		$post_1 = get_post($title);
    		$values = get_post_meta( $title, 'du_meme_auteur', true);
    			echo '<ul>
    foreach($values as $agrege)
    				wc_get_template_part( 'content', 'product' );  
    			echo '</ul>';
    		// always good to see exactly what you are working with
    add_action( 'woocommerce_after_single_product_summary', 'relation_product' );

    The var_dump result is : array(3) { [0]=> string(4) “1208” [1]=> string(4) “1114” [2]=> string(4) “1102” }

    Thanks a lot for help!

  • This is because you are using get_post_meta() instead of get_field()

    ACF only stores the post IDs of the posts in a relationship field. These IDs are stored as strings. When you use get_post_meta() you can only get what ACF stores. If you want ACF to do the work of getting the post objects then you need to use the ACF functions.

  • Thanks a lot!

    I replace :
    $values = get_post_meta( $title, 'du_meme_auteur', true);
    $values = get_field('du_meme_auteur', $title, true);

    and now my array is returning post object.

    Thanks again!

    There is still a tricky issue to display it with :

    foreach($values as $agrege)
    				setup_postdata( $GLOBALS[$agrege]); 
    				wc_get_template_part( 'content', 'product' );  
    			echo '</ul></div></div></div>';

    but I avoid the problem with displaying it a different way. `


Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Relationship returns array of string instead of post object’ is closed to new replies.