I am trying to execute a query using the below code but I'm getting empty array in var_dump.

global $wpdb;
global $post;
$slug = $post->post_name;

$course = $wpdb->get_results( "SELECT * FROM wp_posts where post_name = $slug" );
var_dump($course);exit; // 

If I run the same query in PHPMyAdmin it returns 2 records:

SELECT * FROM wp_posts where post_name = "course-1"; // this returns 2 records

I also vardump $slug = $post->post_name; in code and it is return the below

string(8) "course-1"

1 Answer 1


you may need to wrap $slug in quotes

$course = $wpdb->get_results( "SELECT * FROM wp_posts where post_name = '$slug'" );
  • 1
    If you're using $wpdb, it's best to get in the habit of using $wpdb->prepare() too. In this case, $course = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM wp_posts WHERE post_name = %s', $slug ) );
    – Pat J
    Jun 12, 2020 at 18:25

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.