Support » Plugins and Hacks » Hacks » Trying to query posts by isset variable

  • 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

Viewing 1 replies (of 1 total)
  • 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

Viewing 1 replies (of 1 total)
  • The topic ‘Trying to query posts by isset variable’ is closed to new replies.