I have two WordPress post types the normal ‘post’ and a custom post type called ‘notes’. I want to combine both and sort them by date. I managed to find the combine query and that’s working fine. The problem is I’d like to have different styling for notes. I thought I could do a wordpress if_singlular(‘notes’) to try and target it.. but I’m guessing it’s getting lost when the merge happens.
Does anyone know how I could achieve this functionality?
Many thanks!
My php:
<?php
// An example of creating two separate WP queries, combining the results,
// sorting by date and formatting the results for us in a loop like a regular query.
// order the posts by date in descending order (should go in functions.php to keep things tidy)
function order_by_date( $a, $b )
{
return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
'post_type' => 'notes',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );
usort( $final_posts, 'order_by_date' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
echo '
<article class="item shortNote">
<div class="snMeta clearfix">
<img src="'.get_bloginfo('template_url').'/assets/images/sn-icon.png" alt="Short Note" />
<span class="metaDate">'. get_the_date('M / d / Y').'</span>
<strong>Short Note</strong>
</div>
<h2><a href="'. esc_attr( esc_url( get_the_permalink() ) ) .'">'.get_the_title().'</a></h2>
</article>';
}
}
?>
Ok so this should do it:
I just had to test it on my server to see if it works. So I added the
$post_type
variable that should return the post type, and then I just put that in your class in the<article>
tag, so you can differentiate 🙂Tip:
When in doubt what your loop outputs, always do
print_r()
. This will show you what you are dealing with (arrays, strings, objects) so you easily know what to target 🙂Hope this helps.