0

I'm trying to create a plugin for displaying post titles and dates (which will be displayed as links to those posts) of a specific date range and category. So far I have managed to get to display the posts in between the dates, but I can't wrap my head around the WP category thing. I have no idea how to connect those two into a single SQL query. Here's the code so far:

function izvjestaj($attr) {
    global $wpdb;
    $start .= $attr['godina'] . "-09-01";
    $end .= $attr['godina'] + 1 . "-08-31";
    $cat = $attr['cat'];

    $posts = $wpdb->get_results("
        SELECT * 
        FROM wp_posts, wp_terms 
        WHERE post_date 
        BETWEEN '$start' AND '$end' 
        ORDER BY post_date");

    foreach($posts as $post): 
        echo "<a href='./?p=" . $post->ID . "'>" . $post->post_date . " " . $post->post_title . "</a><br />";
    endforeach;
}
add_shortcode('izvjestaj', 'izvjestaj');

So basically I want to create a plugin that can be used with the shortcode:

[izvjestaj godina=2010 cat=some_category]

and that it displays the titles and dates of those posts. Basically a report of posts.

(translations cro>eng : 'godina' = 'year', 'izvjestaj' = 'report')

1 Answer 1

1

Please try the following code:

Following code has to be added in shortcode function

 global $wpdb;
    $start .= $attr['godina'] . "-09-01";
    $end .= $attr['godina'] + 1 . "-08-31";
    $cat = $attr['cat']; //$cat must be category name.
    $cat_term_id=get_term_by('name', $cat, 'category');
    $term_id=$cat_term_id->term_id;
    $query = array(
      'post_type' => 'post', 
      'tax_query' => array(array( 'taxonomy' => 'category',
                               'field' => 'term_id',
                               'terms'=>$term_id
                               )),

      'post_status' => 'publish',

      'date_query'     => array(
                                array(
                                    'after'     => $start,
                                     'before'    => $end,
                                     'inclusive' => true,
                               )
                        )
    );

$query_str = new WP_Query( $query );
3
  • Please add a proper explanation to your code. Also don't post multi answers. Rather edit the original answer Nov 4, 2014 at 10:11
  • I've tried it, I get no errors this time but I also don't get any posts back and I've tried with several years and categories.
    – Vedran
    Nov 4, 2014 at 10:52
  • My upper comment is my own fault. I tried the code in a hurry between lectures and totally forgot to actually DISPLAY the results. It works perfectly now, thank you very much!
    – Vedran
    Nov 4, 2014 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.