从$ wpdb获得正确的价值

Before creating new post programmatically I want to check if there is a post with the same headline in my database.

I am checking that like this:

$results = $wpdb->get_results("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'candidates' AND post_title = '$name'");

Example of value I get when I var_dump($results):

array(1) { [0]=> object(stdClass)#85 (1) { ["COUNT(*)"]=> string(1) "8" } }

Now I want to get that string(1) "8", add it to variable and convert it to number, but I am not sure how to get it.

I tried something like

$number = (int)$results[0]->COUNT(*) 

but that isn't right. I also tried some other combinations but couldn't figure it out

Your very problem is the (*) in $number = (int)$results[0]->COUNT(*). You cannot use these special characters simply as 'variable'. You're better off using a column alias using AS your_column_alias.

So you want to use

SELECT COUNT(*) as post_count FROM $wpdb->posts  WHERE post_type = 'candidates' AND post_title = '$name'

as query and

$number = (int) $results[0]->post_count;

to fetch the aliased column from your resultset.