0

I have a custom post type with a custom taxonomy.

I am currently displaying all the posts sorted by date with a header of the date above all the posts using this code:

<?php
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'press' AND post_status = 'publish' GROUP BY year DESC" );

foreach ( $years as $year ) {

    $posts_this_year = $wpdb->get_results( "SELECT ID, post_title FROM wp_posts WHERE post_type = 'press' AND post_status = 'publish' AND YEAR(post_date) = '" . $year->year . "'" );

    echo '<div id="press-year">' . $year->year . '</div>';



    foreach ( $posts_this_year as $post ) {


echo '<div id="small_gridbox1">';


$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID),         thumbnail, false);
echo '<div id="small_gridbackground" style="background-image: url(';
echo $src[0];
echo ')"> </div> 

<a href="';
the_field('pdflink');
echo '" target="_blank"> <div id="small_gridcontent">

 <div class="small_title">';
the_title();
echo '<div class="job_title">';
the_field('title');
echo '</div></div>
<div class="small_sub">';
echo str_replace(' ', '', get_field('sub_heading'));
echo '</div>

</div>
  </a>
</div>';
    }

}
 ?>

I cannot seem to be able to get just the post with a certain taxonomy on the archive pages.

Ideally I would like to use the code I have but some how combine it with this code which I have used successfully in the past:

  <?php $term = get_term_by( 'slug', get_query_var( 'term' ),
get_query_var( 'taxonomy' ) ); ?>

Can anyone offer any insight?

2
  • Please correct your formatting so this is easier to read/understand. – Megan Feb 25 '16 at 4:19
  • If you add spaces (or just copy them), it will line up! The line breaks could be cleaned up, too. Aside from formatting, have you taken a look at this method of looping through custom taxonomies: wordpress.stackexchange.com/a/204664/84643 You could use WP_Query to specify taxonomy and the date_query parameter to specify the year. – Megan Feb 25 '16 at 4:30
3

You are over-complicating everything here. What you are doing is not just expensive (because you loose all caches which include post, post meta, term and thumbnail caches), it is totally wrong as well.

  • You are running custom queries which replaces the main query. This in itself makes your page load slower

  • You shouldn't be running your own SQL queries for security purposes and dynamica. As I said, you loose all caches which makes page loads faster and reduces db queries. You also loose all the filters and actions that WP_Query offers

  • You are running a lot of unnecesarry queries. Everything you need to do is already in the main query, it is just a case of using that info to suite your needs

Lets look at how we are going to solve this. The main query on a taxonomy term archive page already only returns posts from the queried term. These posts by default are ordered by date, DESC. So the newest posts will be on top and the dinosaurs at the bottom. As you can see, everything is already there, all you might need to do is to alter the amount of posts to show per page, which in this case seems to be all of them on page one

Because we use the main query here, all post caches are filled with our posts, post meta and term info, which saves a lot on db queries later on. Also, because we use the main query, our post thumbnails are also cached. Remember, post thumbnails are only cached for the main query, and not for custom queries.

First, let use pre_get_posts to get all posts on page one on our taxonomy term archive pages

add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin()         // Only target front end
         && $q->is_main_query() // Only target the main query
         && $q->is_tax()        // Only target taxonomy term archive pages
    ) {
        $q->set( 'posts_per_page', -1 ); // Will return all posts on page one
    }
});

If you where using the main default loop, you would have seen all posts returned ordered by date on your taxonomy archive page

Lets sort your loop. First of all, remove all your code. We do not want and do not need the custom queries. We only want to use the main loop. As for the sorting part, it is as easy as comparing post dates and only display the year if this differ between any two posts (NOTE: All code is untested, and I only cleaned up your code, did not alter it)

if ( have_posts() ) {

    // Define a variable which will hold our year value
    $year_variable = '';

    while ( have_posts() ) {
        the_post();

        // Lets get the post date, but only the year value
        $post_year = get_the_date( 'Y' );

        /** 
         * Compare the current post's date with our $year_variable and
         * display the year value if the two dates differs
         */
        if ( $year_variable !== $post_year )
            echo '<div id="press-year">' . $post_year . '</div>';

        // Update the $year_variable value
        $year_variable = $post_year;

        // Now we can display the rest of the loop
        echo '<div id="small_gridbox1">';

            $src = wp_get_attachment_image_src( get_post_thumbnail_id(), thumbnail, false);
            echo '<div id="small_gridbackground" style="background-image: url(
                ' . $src[0] . '
            </div>'; 

            echo '<a href='" . the_field('pdflink') . '" target="_blank
                <div id="small_gridcontent">
                    <div class="small_title">
                        ' . the_title() . '
                        <div class="job_title">
                            ' . the_field('title') . '
                        </div>
                    </div>
                    <div class="small_sub">
                        ' . str_replace( ' ', '', get_field('sub_heading' ) ) . '
                    </div>
                </div>
            </a>';
        echo '</div>';
    }
}

This should give you a basic idea of how your taxonomy archive page should look like

1
  • I know I am quite late to this party. Your approach works really well. I am wondering if there is possibly a way to actually wrap posts from a year inside a div instead of a heading above each year's posts? E.g. <div class="year-2017"><h2>This is 2017</h2> <!-- All posts from current year --></div>. I can't wrap my head around it. – physalis Jul 5 '17 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.