Question

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"
Was it helpful?

Solution

you may need to wrap $slug in quotes

$course = $wpdb->get_results( "SELECT * FROM wp_posts where post_name = '$slug'" );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top