Home Forums General Issues Querying a subfield to retrieve an image


Querying a subfield to retrieve an image

  • I need help querying ACF for a subfield.

    Here is my query:

        $rows = $wpdb->get_results($wpdb->prepare( 
                SELECT * FROM {$wpdb->prefix}postmeta
                WHERE meta_key LIKE %s
                    AND meta_value = %s
                ORDER BY rand()
                LIMIT 3
                'project_media_%_home_slider_img', // meta_name: $ParentName_$RowNumber_$ChildName
                'appears_on_slider' // meta_value: 'type_3' for example
    		if( $rows )
    			foreach( $rows as $row )
    				preg_match('_([0-9]+)_', $row->meta_key, $matches);
    				$meta_key = 'project_media_' . $matches[0] . '_project_image_slider_image'; // $matches[0] contains the row number!
    				//  use get_post_meta to load the image sub field
    				// -
    				$image_id = get_post_meta( $row->post_id, $meta_key, true );
    				// load image src
    				// -
    				$src = wp_get_attachment_image_src( $image_id, 'cropped_image' );
    				<li class="home-slide home-slide--img">
    					<a class="home-slide__anchor" href="<?php echo get_permalink( $row->post_id ); ?>">
    						<img class="home-slide__img" src="<?php echo $src; ?>" alt="<?php echo get_the_title( $row->post_id ); ?>">

    $image_id returns


    I need it to return the cropped image id; so in this case, 393.
    (If I replace ‘$image_id’ with ‘393’, it works, for that id)

    Maybe it’s more complicated than converting ‘{“original_image”:”378″,”cropped_image”:393}’ to ‘393’ but I’m at a dead end.

    Can anybody help?

  • Hi @jonnyboggon

    I’m afraid I don’t quite understand the issue, so please forgive me if I’m wrong.

    The string you got is called serialized string. You can convert it to an array by using the unserialize() function like this:

    $image_ids = unserialize($image_id);
    $cropped_id = $image_ids['cropped_image']

    Because this is more related to PHP, for further support kindly get in touch with PHP community.

    If that’s not what you want, could you please explain the issue again in more detail?

    Thanks 🙂

  • I really appreciate you taking the time to help.

    Posted this on Stackoverflow and got an answer (even though somebody else deleted the right answer before I could thank them).

    For anybody else who comes across this, I need to convert it this way.

    $image_id = get_post_meta( $row->post_id, $meta_key, true );
    					//$image_ids = unserialize($image_id);
    					$json = json_decode($image_id);
    					// load image src
    					// -
    					$src = wp_get_attachment_image_src( $json->cropped_image, 'cropped_image' );

    It was a JSON object which needed to be decoded.

    Thanks again for helping – means a lot to somebody who was completely stuck.

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

The topic ‘Querying a subfield to retrieve an image’ is closed to new replies.