0

I am using WordPress, I have to get the custom post type data using post id and I tried the below code but I am getting the error

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM WHERE 1=1 AND .ID = 972 AND .post_type = 'test' AND ((.post_s...' at line 1]

I am getting query and array output below.

 Array ( [p] => 972 [post_type] => test [post_status] => publish [order] => DESC ) SELECT .* FROM WHERE 1=1 AND .ID = 972 AND .post_type = 'test' AND ((.post_status = 'publish')) ORDER BY .post_date DESC 

I am using the below code

 function postData($wpdb, $parentsdata){
        $args = array(
                      'p' => $parentsdata['utm_id'],
                      'post_type' => 'test',    
                      'post_status' => 'publish',
                      'order'      => 'DESC'
    );
    
      $related = new WP_Query($args);
      print_r($args); // checking parameters
      echo $wpdb->last_query; // query
         
         //$my_post = get_post($parentsdata['utm_id']);
        //echo $my_post->post_title;
    
         wp_reset_query();
     }
7
  • There’s nothing wrong with the code you’ve included but seem to have code somewhere that filters the SQL for queries which has broken WP_Query. Jan 8 at 3:43
  • @JacobPeattie, I am not getting the wp_posts table name in the sql query. Jan 8 at 3:47
  • Is that $wpdb as in function postData($wpdb, the same WordPress database object that normally be accessed using global $wpdb; (from a function)? And try echo $related->request; - what's the output? Also, if you just wanted to get the post data by the ID, you could simply do get_post( $parentsdata['utm_id'] ) ..
    – Sally CJ
    Jan 8 at 4:03
  • @SallyCJ, I tried get_post. I am getting the same error. WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE ID = 972 LIMIT 1' at line 1] SELECT * FROM WHERE ID = 972 LIMIT 1 Jan 8 at 4:07
  • If I add table name(wp_posts) in the SQL query and run it in the PHPMyAdmin then it's working. Jan 8 at 4:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy