Should I worry about SQL injection when using REST API and sql queries via $wpdb?
For example, is the bellow vulnerable to sql injection?

public static function get_post( WP_REST_Request $request ) {
        global $wpdb;
        $post_slug = $request->get_param( 'slug' );
        $sql_post_by_slug = "select * from wp_posts 
                                where post_name='{$post_slug}' and post_status='publish'
                                limit 1;";
        $post = $wpdb->get_results($sql_post_by_slug);

        return $post[0];

            'methods'             => 'GET',
            'callback'            => array('ReactApi','get_post'),
        ) );

I tried to pass ' char in url and I see that it does't work:
...reactapi/v1/post/slug'additional-text turns to ...post_name='slug\\'additional-text'...

1 Answer 1


Yes. This is not secure at all. You're putting user input directly into a database query. You need to use $wpdb->prepare() if you're inserting user input into SQL:

$post_slug = $request->get_param( 'slug' );

$query = $wpdb->prepare(
    "select * from wp_posts where post_name=%s and post_status='publish' limit 1;",

$results = $wpdb->get_results( $query );

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.