Display CPT News in Group of 3 using shortcode WordPress

Display record in group of specific count is some time difficult while you are going to display it with blockquote, ul etc Tag instead of simple Div tag. because in this case it is required that Opening tag must be closed to display it in well format without miss configured it structure.

In Below example i created Custom post type cpt_news with taxonomy cat_news and display it in group of 3 using blockquote tag with registering shortcode to use it in sidebar by custom text widget.

#

add_shortcode('sc_my_news','fn_get_news');  //[sc_my_news category="cricket-news" type="testimonial"]

function fn_get_news($attr)
{
    global $wpdb;
    $html = '
'; $category = $attr['category']; $args = array( 'post_type' => 'cpt_news', 'tax_query' => array( array( 'taxonomy' => 'cat_news', 'field' => 'slug', 'terms' => $category, ), ), ); $newspost = new WP_Query($args); $NumResults = $newspost->post_count; if(!$NumResults>0) { $args = array( 'post_type' => 'cpt_news', 'tax_query' => array( array( 'taxonomy' => 'cat_news', 'field' => 'slug', 'terms' => 'default-news', ), ), ); $newspost = new WP_Query($args); $NumResults = $newspost->post_count; } $count = 1; $html .= '
'; while($newspost->have_posts()): $newspost->the_post(); $postid = get_the_ID(); $html .= ''.get_the_title().''; if($count % 3 == 0){$html .= '
';} // close blockquote if group 3 complete if($count % 3 == 0 && $count<$NumResults) $html .='
'; if($count % 3 != 0 && $count==$NumResults ) $html .='
'; // close blockquote if group 3 not complete but record over $count++; endwhile; $html .= '
'; return $html; }

Leave a Comment

Scroll to Top