Support

Account

Home Forums Gutenberg Conditional to check if an instance of a block is the first on page/post Reply To: Conditional to check if an instance of a block is the first on page/post

  • Hey there, I would do this to get the last block.
    In addition I added a param to get the post we want by ID and a check to avoid error such as “Trying to get property ‘post_content’ of non-object”

    function friss_get_last_block_id($post=null) {
    	if(is_null($post)){
    		global $post;
    	}elseif(is_int($post)){
    		$post = get_post($post);
    	}
    
    	if($post instanceof WP_Post){     
    
    	    if(has_blocks($post->post_content)) {
    	        $blocks = parse_blocks($post->post_content);
    
    	        $last_block = end($blocks);
    	        $last_block_attrs = $last_block['attrs'];
    
    	        if(isset($last_block_attrs['id'])) {
    	            return $last_block_attrs['id'];
    	        }
    	    }
    	}
    	return false;
    }