WordPress.org

Forums

Trying to query posts by isset variable (2 posts)

  1. daveaevion
    Member
    Posted 4 years ago #

    i've been working with this code, trying to assign the variable sort in the url (with links) so that i can change the loop based on what the reader wants to sort the posts by... day, week, month, or year when they click on various links.

    i don't know why it won't work... it is getting the variable fine, but for some reason, assigning $date and then calling it later is not working.

    here's my code:

    <?php
    $sort= isset($_GET['sort']) ? $_GET['sort'] : "A";
    if($sort == "A") {
    $date = '-24 hours';
    }
    elseif($sort == "B") {
    $date = '-7 days';
    }
    elseif($sort == "C") {
    $date = '-30 days';
    }
    elseif($sort == "D") {
    $date = '-365 days';
    }
    else {
    $date = '-24 hours';
    }
    
    function filter_where($where = '') {
    $where .= " AND post_date > '" . date('Y-m-d H:i:s', strtotime($date)) . "'";
    return $where;
    }
    add_filter('posts_where', 'filter_where');
    query_posts($query_string); ?>
    
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    and then it continues on...

    i'm not very good with php, and i appreciate all your help with this. thank you

  2. daveaevion
    Member
    Posted 4 years ago #

    i figured it out... i needed to put the variable within the function. ok, so i guess if you are looking for a way to use links to change the query of your loop, then this code could do the trick...

    <?php
    function filter_where($where = '') {
    $sort= isset($_GET['sort']) ? $_GET['sort'] : "A";
    if($sort == "A") {
    $date = '-24 hours';
    }
    elseif($sort == "B") {
    $date = '-7 days';
    }
    elseif($sort == "C") {
    $date = '-30 days';
    }
    elseif($sort == "D") {
    $date = '-365 days';
    }
    else {
    $date = '-24 hours';
    }
    $where .= " AND post_date > '" . date('Y-m-d H:i:s', strtotime($date)) . "'";
    return $where;
    }
    add_filter('posts_where', 'filter_where');
    query_posts($query_string); ?>
    
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    and then it continues on to what you want to do...

    hope this could help someone who wants to do something similar

Topic Closed

This topic has been closed to new replies.

About this Topic