Aaron Harker
Aaron Harker

Reputation: 321

Having Trouble Running A Custom Query In Wordpress

OK I've been staring at this for hours and I can't see anything wrong. I'm hoping one of you super bright people can see my mistake. I have copied the select statement and and run it on PHPMYAdmin and it runs ok there but it returns no results in Wordpress. I have also verified that the 2 variables are populated correctly.

$user = wp_get_current_user();
$terms = wp_get_object_terms($user->ID, 'departments');
$term = $terms[0]->term_id;

$results = $wpdb->get_results(
        $wpdb->prepare(
        "SELECT post_title, post_content
        FROM wp_posts
        INNER JOIN wp_postmeta ON wp_posts.id = wp_postmeta.post_id
        INNER JOIN wp_term_relationships ON wp_posts.id = wp_term_relationships.object_id
        WHERE post_type = 'events'
        AND meta_key = 'event_date'
        AND meta_value = %s
        AND term_taxonomy_id = %s"),array($date,$term));

If I do a var_dump of $results I just get NULL.

Upvotes: 3

Views: 321

Answers (1)

mikerojas
mikerojas

Reputation: 2338

There is an error in your prepare statement... array($date,$term) needs to be inside the prepare function.

Example

// Bad- args outside of prepare
$results = $wpdb->get_results($wpdb->prepare($sql), $args);

// Good- args inside prepare
$results = $wpdb->get_results($wpdb->prepare($sql, $args));

Relevant Docs

Solution for Your Code

$user = wp_get_current_user();
$terms = wp_get_object_terms($user->ID, 'departments');
$term = $terms[0]->term_id;
$results = $wpdb->get_results(
  $wpdb->prepare(
    "SELECT post_title, post_content
    FROM wp_posts
    INNER JOIN wp_postmeta ON wp_posts.id = wp_postmeta.post_id
    INNER JOIN wp_term_relationships ON wp_posts.id = wp_term_relationships.object_id
    WHERE post_type = 'events'
    AND meta_key = 'event_date'
    AND meta_value = %s
    AND term_taxonomy_id = %s",
    array($date,$term)
));

Upvotes: 2

Related Questions