Use sql query in str_replace

38
October 28, 2018, at 8:40 PM

I have a code for getting post title like this:

$content = str_replace('%title', $post->post_title, $content );

I'd like to use my own title from database.
I wrote this code:

        global $wpdb;
        $mycontent = $wpdb->get_var(
            'SELECT `meta_value` FROM `wp_postmeta` WHERE `post_id` = '.$post->ID.' AND `meta_key` = \'my_seo_title\';'
        );
        $content = str_replace('%my_seo_title', $mycontent , $content);


Does it make a security problem?

Answer 1

Does it have security issue?

In the unlikely event that your $post object gets replaced with something else (and at that point I'd consider the website's security as already compromised), the attacker could replace the value returned by $post->ID with a malicious query string (a.k.a. SQL Injection).

To avoid that, as everyone else already pointed out, you should escape your query using the prepare() method from the $wpdb object:

$mycontent = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT `meta_value` FROM `wp_postmeta` WHERE `post_id` = %d AND `meta_key` = %s;",
        array( $post->ID, 'my_seo_title' )
    )
);

Out of curiosity, why are you manually retrieving the meta value from the database when we already have the get_post_meta() function (which does the whole security check automagically for you)? I mean, you could replace your code with:

$mycontent = get_post_meta( $post->ID, 'my_seo_title', true );

... and forget about writing queries by hand and/or making them secure (when not necessary).

READ ALSO
Remove (optional) text from fields on My account edit address in Woocommerce 3.4+

Remove (optional) text from fields on My account edit address in Woocommerce 3.4+

I'm trying to remove the <span class="optional">(optional)</span> from the WooCommerce My Account edit address pageIs there an other way to do it like this?

52
Error when loading scripts in Wordpress admin

Error when loading scripts in Wordpress admin

I am using Wordpress Images Gallery and each time I try to add new images I get this error in the console:

37
Fetch and echo data from second table based on value inside first table

Fetch and echo data from second table based on value inside first table

I am trying to create a table/chart that has customers information in it

42
Discount on specific products based on a daily time range in Woocommerce

Discount on specific products based on a daily time range in Woocommerce

I am trying to make have a "Lunch Special" daily event on my WooCommerce websiteThis means that from 11h00 to 15h00, specific products would be discounted due to this "Lunch Special" daily event

61