Support

Account

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

Solved

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);
    		if($values){
    			echo '<ul>
    foreach($values as $agrege)
    			{
    				
    				setup_postdata($agrege); 
    				wc_get_template_part( 'content', 'product' );  
    			}
    			echo '</ul>';
    			wp_reset_postdata();
    
    		}
    		// always good to see exactly what you are working with
    	var_dump($values);
    	}
    	
    }
    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() https://www.advancedcustomfields.com/resources/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);
    by
    $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>';
    			wp_reset_postdata();

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

    Cha

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.