WordPress.org

Ready to get started?Download WordPress

Forums

MySQL request before start of Loop (4 posts)

  1. CounterDax
    Member
    Posted 6 years ago #

    Hi all...
    I have a slight problem with trips to the DB and the loop, that I cannot solve using the tricks described in the codex.

    At the beginning of my template files I need query the DB twice to generate a "timeline" of posts. Since I'm requesting specific info I am unable to use WP_Query or anything like that. So, I do the following:

    // Get the current year, either of the page or of actual date
    $y = get_the_time('Y');
    if(empty($y)) { $y = date('Y'); }
    $year = $wpdb->escape($y);
    
    // Get all distinct years with posts
    $yresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) as 'year'
     FROM $wpdb->posts
     WHERE post_type = 'post'
     AND post_status = 'publish'
     ORDER BY post_date ASC");
    
    foreach($yresults as $yresult) {
    	$tl_years[] .= $yresult->year;
    }
    
    // More unimportant stuff happens here
    
    // Now get all the posts within this year
    $mresults = $wpdb->get_results("SELECT ID, post_date, post_title, MONTH(post_date) as 'month'
     FROM $wpdb->posts
     WHERE post_type = 'post'
     AND post_status = 'publish'
     AND YEAR(post_date) = $year
     ORDER BY post_date ASC");
    
    // Loop through $mresults
    if($mresults) {
    	foreach($mresults as $mresult) {
    
    	// we apply some styling and using this create some variables
    	    that we add to the page later-on (one in the <head>, the other
    	    in the <body>
    
    	}
    }
    // return the variables

    Now, this thus messes up the regular wordpress loop. I can use query_posts() but this won't do much because then I will use the date based hierarchy structure of the blog.
    Does anyone know I can work around the loop or solve this problem in some other way?

    P.S. The backticks in the SQL queries have been changed to ' in the code example above (otherwise we'll see in stead).

  2. haochi
    Member
    Posted 6 years ago #

    Well, looking at the code it seems like that you can just connect to the DB directly without using wordpress functions.

  3. CounterDax
    Member
    Posted 6 years ago #

    Well, I am using some WP template tags in the code, such as get_year_link() and the_permalink()... it's going to be hard to work around that.

  4. CounterDax
    Member
    Posted 6 years ago #

    Well, I did it. Haochi, I listened to your advice and I'm nearly done with coding everything as a direct connection to the DB. Thanks.

Topic Closed

This topic has been closed to new replies.

About this Topic