• Resolved Phil McDonnell

    (@philmcdonnell)


    Hey All,

    I am trying to get the ID of a post by looking it up via the post_name but for some reason this code is not getting any results. If I put the actual post_name as a string in here it works. What gives? Any ideas?

    $order_idd = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_name = $order_numm" );

    Thanks,
    Phil

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hello you could do it like this I suppose, be aware that you read the ‘slug’ not the ‘title’ of the post:

    <?php
    	global $wpdb;
    	$post_slug = 'hello-world';
    	
    	$results = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE post_name = '$post_slug'", OBJECT );
    	
    	echo '<pre>';
    	print_r( $results );
    	echo '</pre>';
    ?>

    But I don’t know the whole concept here so if you are already inside a loop there should be an even easier way with the core functions that WordPress already has just in case you don’t want to run custom queries.

    Where is $order_num coming from? The variable name implies a number of some sort, which wouldn’t be right for post_name, and if it works if you type it in manually, that implies the issue is with the variable.

    Also note from Xenos’ answer the ' quote marks around the value you’re looking up. If it’s a string you’ll probably need those.

    Thread Starter Phil McDonnell

    (@philmcdonnell)

    OMG! Thank you both! It was 5am here when I was working on this and my eyes were just crossing…

    So it turns out that the $order_numm is in fact a string, once I added the ‘ ‘ around the variable it worked!

    You guys rock! Thank you so much…

    Regards,
    Phil

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WPDB not returning results’ is closed to new replies.