I'm using the following custom plugin to count the number of members in the MemberPress database:

function display_member_count( $atts ) {

    global $wpdb;
    $sql = "SELECT COUNT(`meta_key`) as count FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = '" . $atts[0] . "';";
    $myrows = $wpdb->get_results($sql);
    $member_count = $myrows[0]->count;

    return $member_count;

add_shortcode( 'member-count', 'display_member_count' );

I would then use the shortcode [member-count nsw] to display the number of members in NSW.

Do I need to sanitize $atts? If so, how please?

Help appreciated.

1 Answer 1


Of course you do have to sanitize it and escape it.

Otherwise any author/editor of the site will be able to perform any query on your database.

First of all you should never create SQL queries like you do in your code. Never concatenate the raw SQL with anything that is variable or comes from user.

You should use $wpdb->prepare for that.

So your code should look more like that:

$sql = "SELECT COUNT(meta_key) as count FROM {$wpdb->usermeta} WHERE meta_key = %s && meta_value = %s";
    $member_count = $wpdb->get_var( $wpdb->prepare( $sql, 'mepr-address-state', $atts[0] ) );

As you can see, there is also no point in getting all rows (there’s only one) and there’s no point in getting all columns (there also is only one).

That’s the escaping part that will save you from SQL injections.

But yes - most likely you should also put some validation in there - but it depends on what are the available values for that param.

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.