Forums

query_posts function question (5 posts)

  1. sacqigong
    Member
    Posted 1 year ago #

    I'm trying to do something simple, maybe there's another way, but I'm looking to show posts on my main page for the last 2 (or 3) months. The below code works for one previous month:

    --------------
    $current_month = date('m');
    $current_year = date('Y');

    // Routine to deal with January
    if ($current_month == 1)
    { $current_month = 13;
    $current_year = date('Y') - 1;
    }

    // So go back one month
    $current_month = $current_month - 1;

    query_posts("year=$current_year&monthnum=$current_month&order=ASC");

    ------------

    But trying to pull the last 2 months, even using this, doesn't work:
    query_posts("year=$current_year&monthnum=7,8&order=ASC");

    Any idea how i can embed 2 months or even a BETWEEN in the query_posts

  2. Otto42
    Moderator
    Posted 1 year ago #

    You can't. WordPress does not support ranges of dates like that.

  3. sacqigong
    Member
    Posted 1 year ago #

    Ah ha. Cool, thanks for the response. Do you know of any other way to accomplish what I'm looking to do, or am I out of luck?

  4. Ogre
    Member
    Posted 1 year ago #

    Mysql supports date math:

    select date_sub(curdate(), interval 2 month);

    The function curdate() returns the current date. When specifying the interval note that 'month' is not plural.

    It should be possible to create a query that returns all posts for a given period. Unfortunately, you'll have to get your hands dirty digging in the code.

  5. sacqigong
    Member
    Posted 1 year ago #

    Thanks for the reply Ogre. In the meantime I got dirty and figured out a way to do this.

    In my query.php, I created a new if statement:

    ------------
    // Added by Scott for mulit-month searches
    if ( $q['mult_month'] )
    $where .= " AND MONTH($wpdb->posts.post_date) BETWEEN " . $q['monthnum1'] . " AND " .$q['monthnum2'] . "";
    ------------

    and inserted in above these lines in that file:
    if ( '' !== $q['hour'] )
    $where .= " AND HOUR($wpdb->posts.post_date)='" . $q['hour'] . "'";

    if ( '' !== $q['minute'] )
    $where .= " AND MINUTE($wpdb->posts.post_date)='" . $q['minute'] . "'";

    Then, in my index.php, I call a script that determines the date range I want and runs the query_posts, the code looks like this:

    query_posts("year=$current_year&mult_month=1&monthnum2=$current_month&monthnum1=$last_month&order=DESC&posts_per_page=-1");

    The above references the mult_month variable to use the modified SELECT statement portion from query.php, then my monthnum1 and monthnum2 are the range for the date I need.

    This will actually give me some possible trouble around December, so I might have to rework it....argh.

    I will look into the function you refer to, thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic