• Resolved batters22

    (@batters22)


    I have a custom post type called Supporter. I’ve created a new block with lazyblocks which contains a text description field and an image field, and a locked template for the Supporter post type. This works fine.

    The Supporter post type is used (jus) to render a list of Supporters in a few different ways in different areas of the website.

    I’m doing this by running a custom query which retrieves an array of supporter data. Specifically I want this to contain the description field and the ID of the image.

    //$wp_query populated from custom post type
    
    while ( $wp_query->have_posts() ) : $wp_query->the_post();
    	
    		$content = parse_blocks(get_the_content());
    		
    		$block = $content[0];
    		
    		$blockContent = $content[0]['attrs'];
    		
    		$supporters[] = array(
    		
    			'title' => get_the_title(),
    			'description' => $blockContent['description'],
    			'imageID' => $blockContent['image']
    		
    		);
    
    	endwhile;

    Title and description fine. I’m running into an issue retrieving the ID. As I understand it, the image block type is stored as an array, with id as one of the keys. But the array seems to be flattened into a string, so $blockContent[‘image’] is populated with:

    %7B%22alt%22:%22%22,%22title%22:%22harwell%22,%22caption%22:%22%22,%22id%22:831,%22link%22:%22https://myurluk/supporter/supporter-4/harwell/%22,%22url%22:%22https://myurl.uk/wp-content/uploads/2020/06/harwell.jpg%22%7D

    Any suggestions on how I can extract the ID from this?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter batters22

    (@batters22)

    OK, got it……the stored value (I think) is a urlencoded json array…so it needs to be decoded twice. This works:

    	while ( $wp_query->have_posts() ) : $wp_query->the_post();
    	
    		$content = parse_blocks(get_the_content());
    		
    		$blockContent = $content[0]['attrs'];
    		
    		$image_json = urldecode($blockContent['image']);
    		$image_object = json_decode($logo_json);
    	
    	
    		$supporters[] = array(
    		
    			'title' => '<h3>'.get_the_title().'</h3>',
    			'description' => '<p>'.$blockContent['description'].'</p>',
    			'imageId' => $image_object->id
    		
    		);
    
    	endwhile;
    Plugin Author nK

    (@nko)

    Hey.

    I’m glad that you resolved this issue already. Yes, saved value is encoded. We manually decode it here – https://github.com/nk-o/lazy-blocks/blob/9a1d6a1a9a65c9f485fc22b7448a039a2cc4839b/src/controls/image/index.php#L75

    Regards, nK.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Accessing image ID from lazyblock in custom query’ is closed to new replies.