• Resolved rose18

    (@rose18)


    Hi,

    I was wondering if it’s possible to use block patterns inside php WP query loop?
    I’ve tried it (see code below), but the it’s returning nothing.

    <?php
    // WP_Query arguments
    $args = array(
    	'post_type'              => array( 'post' ),
    	'posts_per_page'         => -1,
    	'order'                  => 'DESC',
    	'orderby'                => 'date',
    );
    
    // The Query
    $query = new WP_Query( $args );
    
    // The Loop
    if ( $query->have_posts() ) {
    	while ( $query->have_posts() ) {
    		$query->the_post();
    		?>
    		<!-- wp:group {"layout":{"type":"default"}} -->
    		<div class="wp-block-group"><!-- wp:post-title /-->
    
    		<!-- wp:post-date {"style":{"elements":{"link":{"color":{"text":"var:preset|color|red"}}}},"textColor":"red","fontSize":"small"} /-->
    
    		<!-- wp:post-excerpt {"excerptLength":25} /--></div>
    		<!-- /wp:group -->
    		<?php
    /* PHP block pattern file */
    include 'loop-item-post.php';
    
    	}
    }
    
    // Restore original Post Data
    wp_reset_postdata();
    
    ?>

    The core blocks (such as ‘title’, ‘date’ and ‘excerpt’) are not displaying anything on the front-end.

    thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • I believe you can achieve this by using the function render_block() (documentation). If you want to manually render blocks within PHP, you need to convert the block markup into rendered HTML.

    Example expanding the code you provided:

    <?php
    // WP_Query arguments
    $args = array(
        'post_type'              => array('post'),
        'posts_per_page'         => -1,
        'order'                  => 'DESC',
        'orderby'                => 'date',
    );
    
    // The Query
    $query = new WP_Query($args);
    
    // The Loop
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
    
            // Define your block pattern as a string
            $block_pattern = '<!-- wp:group -->
            <div class="wp-block-group"><!-- wp:post-title /-->
    
            <!-- wp:post-date {"style":{"elements":{"link":{"color":{"text":"var:preset|color|red"}}}},"textColor":"red","fontSize":"small"} /-->
    
            <!-- wp:post-excerpt {"excerptLength":25} /--></div>
            <!-- /wp:group -->';
    
            // Parse the block pattern
            $blocks = parse_blocks($block_pattern);
    
            // Render each block
            foreach ($blocks as $block) {
                echo render_block($block);
            }
        }
        wp_reset_postdata();
    }
    ?>
    Thread Starter rose18

    (@rose18)

    WOW! Thank you @joa-kim! It works!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Use block patterns in WP_Query php’ is closed to new replies.