WordPress.org

Ready to get started?Download WordPress

Forums

custom layout for posts category (4 posts)

  1. pybiru
    Member
    Posted 1 year ago #

    Hi,

    I need to display a posts category a particular way. The following format.

    <2013>
    <postname> <postname> <postname>

    <2012>
    <postname> <postname> <postname>

    <2011>
    <postname> <postname> <postname>

    etc..

    I have the following code that works well, but it's pulling in all the posts, I need to filter it so it only pulls in from 1 category.

    <?php
    			// get years that have posts
    			$years = $wpdb->get_results("SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post'
    					AND post_status = 'publish' GROUP BY year DESC");
    
    			foreach($years as $year) {
    			    // get posts for each year
    			    $posts_this_year = $wpdb->get_results("SELECT post_title FROM wp_posts WHERE post_type = 'post'
    			    	AND post_status = 'publish'
    			    	AND YEAR(post_date) = '" . $year->year . "'");
    
    			    echo '<h2>' . $year->year . '</h2><ul>';
    			    foreach($posts_this_year as $post){
    			    	echo '<li>' . $post->post_title . '</li>';
    			    }
    			    echo '</ul>';
    			}
    		?>
  2. bcworkz
    Member
    Posted 1 year ago #

    Why not use WP_Query instead to get posts of a certain year and category? The syntax for that is fairly simple. To do the same using $wpdb, you need to join in the terms and taxonomy tables. I'm afraid I couldn't tell you how to do that.

  3. pybiru
    Member
    Posted 1 year ago #

    Thanks bcworkz. I'll look into WP_Query. Was not too familar with it. Syntax is something like...

    $query = new WP_Query('category_name=food, sort_by=year');?

  4. bcworkz
    Member
    Posted 1 year ago #

    Close. The direct replacement for your query, but by the food category, would be
    $posts_this_year = new WP_Query("category_name=food, year=$year");
    sort_by isn't a valid parameter, but you could orderby=date, and by hooking the 'posts_groupby' filter you could possibly group by year, thus enabling the whole thing to be done in one query, but a few other tweaks would be needed too.

Topic Closed

This topic has been closed to new replies.

About this Topic