• Resolved rose18

    (@rose18)


    I would like to create something similar to Elementor Pro where you can create loop item templates using the Elementor page builder to build the layout. It generates a shortcode that you can use anywhere, such as inside the WP_Query. The example below works.

    $args = array(
    	'post_type'              => array( 'news-post' ),
    );
    
    $newsQuery = new WP_Query( $args );
    
    if ( $newsQuery->have_posts() ) {
    	while ( $newsQuery->have_posts() ) {
    		$newsQuery->the_post();
    		echo do_shortcode('[elementor-template id="942"]');
    	}
    } 
    
    wp_reset_postdata();

    I would like to create a loop template using the block editor, then use that template inside the PHP WP_Query.
    I did try to create a CPT call ‘Templates’ and each post are different templates. I’ve created a simple template, and I’ve used the core block ‘Post Title’, so it will display the dynamic title.
    I’ve also tried to create the shortcode to output the template with the code below, but it’s not working. It’s displaying the content from the template, instead of displaying the dynamic content (which are the news titles).

    add_shortcode( 'my-block-template', 'block_template_content_shortcode' );
    function block_template_content_shortcode($atts) {
    	$atts = shortcode_atts(
    			array(
    					'id' => '',
    			), $atts );
    
    	$field =  $atts['id'] ;
    
    	if ( '' === $field ) {
    			$field = '';
    	}
    
      ob_start();
      if ( post_type_exists( 'block-template' ) ) {
    
        $args = array(
        	'p'                      => $field,
        	'post_type'              => array( 'block-template'),
        	'post_status'            => array( 'publish' ),
        	'posts_per_page'         => '1',
        	'order'                  => 'DESC',
        	'orderby'                => 'date',
        );
    
        $blockTemplateQuery = new WP_Query( $args );
    
        if ( $blockTemplateQuery->have_posts() ) {
        	while ( $blockTemplateQuery->have_posts() ) {
        		$blockTemplateQuery->the_post();
            $post_id = get_the_ID();
            //the_content();
            the_content($post_id );
        	}
        } 
        wp_reset_postdata();
        $content = ob_get_contents();
     }
    	ob_end_clean();
    	return $content;
    }


    I am not sure how to create the shortcode to show the dynamic content. Can someone point me in the right direction so that I can use the template that I’ve created with the block editor in the WP_Query ?

    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Create a loop template (using blocks) and use it inside WP_Query’ is closed to new replies.