WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Shortcode to Query custom Post-type (3 posts)

  1. francoeurdavid
    Member
    Posted 4 months ago #

    Hi,

    I followed this to add a content-block to my theme. I want to extend it with the Shortcodes.

    I want to be able to write :
    [content_zone name="col-1"]

    The code should return the content of the content-block directly where the Shortcode is place within the page. My functions.php look as follows :

    function content_zone_func( $atts ) {
    	extract( shortcode_atts( array(
    		'name' => ''
    	), $atts ) );
    
    	return get_content_zone($name);
    
    }
    function get_content_zone( $name ){
    
    	$content_block = new WP_Query(array('post_type'=>'content-block', 'posts_per_page'=>1, 'content-position'=>$name));
    
    	if($content_block->have_posts()){
    		$content_block->the_post();
    		$content = the_content();
    		wp_reset_postdata();
    	  	return $content;
    	}
    }
    add_shortcode( 'content_zone', 'content_zone_func' );

    The things return the good content but it is not placed correctly in the page. Let's say I use this content in my page :

    Hello, this is the content of the zone :
    [content_zone name="col-1"]
    There you go.

    It would be posted like this on the page :

    CONTENT OF THE ZONE
    
    Hello, this is the content of the zone :
    There you go.

    It looks like the main loop is overrided by this secondary loop.

    If I replace the function by simply returning a string, everything works fine.

  2. bcworkz
    Member
    Posted 4 months ago #

    You need to use get_the_content(). the_content() immediately echoes content, it is not returned as you are expecting.

    You should reset post data regardless if there are posts or not.

  3. francoeurdavid
    Member
    Posted 4 months ago #

    AWWW thank you very much.

Reply

You must log in to post.

About this Topic