I have CPT called "investment" and I want to display all the posts in that CPT by their category. I'm doing that via shortcode.
e.g. [myshortcode type_of_post="investment" cat="12,30"]
and I want it to display posts as below
Category 12
- post1
- post2
Category 30
- post3
- post4
The problem that I have right now is that it shows all the posts but I'm struggling to separate posts by their categories.
This is how it shows right now:
- post1
- post2
- post3
- post4
Here's my code:
// define attributes
extract( shortcode_atts( array (
'cat' => '',
'type_of_post' => '',
'orderby' => 'date',
), $atts ) );
Separate posts
if($type_of_post){
$args['post_type'] = $type_of_post;
}
if($cat) {
$args['category__in'] = array_map('intval',explode(',',$cat));
}
Query
$query = new WP_Query( $args );
if( $query->have_posts() ){
echo "<div class='row col-div investment'>";
while( $query->have_posts() ){
$query->the_post();
$id = get_the_ID();
$page = get_post($id);
$image = get_the_post_thumbnail_url($id);
display_layout($page,$image); //calls the function below
}
echo '</div>';
}
Display posts
function display_layout($page,$image) {
echo "<div class='col-sm-6 pair-cards'>
<div class='sub-div'>
<div class='card-img'>
<a href='$page->post_name'><img src='$image' alt='$page->post_name' /></a>
</div>".
"<div class='entry-title'><a href='$page->post_name'>" . $page->post_title . "</a></div>
<div class='card-desc'>".
"<p>" . strip_tags($page->post_excerpt) ."</p>
</div>
<div class='read-more'>
<a href='$page->post_name'> Read More </a>
</div>
</div>
</div>";
}
I hope I've explained my problem clearly.