WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm a PHP / JavaScript developer and I'm new to WordPress. Our company's website is build upon WordPress. However I created many custom PHP pages without minding the WordPress framework much.

When creating forms to edit things, like posts, I notice that a lot of things don't work properly with a $wpdb->query(insert some SQL here) but often do work with the WordPress wp_update_post() or update_post_meta(), etc.

I wonder if this is because custom queries require a nonce check? I'm also new to nonces, but I'm often confused when working with SQL to get or edit data from the WordPress database how and when I would nonces.

On the other hand, don't any of the WordPress functions special nonce checks?

share|improve this question
up vote 5 down vote accepted

You might be a little confused as to the purpose and function of nonces in WordPress.

Recommended reading:

A nonce is a "number used once" to help protect URLs and forms from certain types of misuse, malicious or otherwise.

Nonces help you ensure, somewhat, the validity of the request being made to a given URL and or the use of a particular form to submit data, whether that be on the backend or frontend.

It doesn't have any bearing on the use of wpdb class.

As evidenced in your previous question your query was not working due to improper SQL synatx.

A good rule to follow is that URLs or forms, especially those that perform any actions on your database should always be accompanied by a nonce that you can verify the request validity against.

Then when inserting data into the database, if you must write raw SQL queries, then you should only use the wpdb class, in particular $wpdb->query() method along with the $wpdb->prepare() method to project against SQL injection: Protect_Queries_Against_SQL_Injection_Attacks

Under the hood, when using functions like wp_insert_post or wp_update_post, WordPress calles either $wpdb->insert() or $wpdb->update() which in turn calls $wpdb->query( $wpdb->prepate() ), so it takes care of sanitization for you.

This is why it is recommended to use the core functions of WordPress when inserting or updating posts, postmeta, users, usermeta and so forth.

In summary, be sure to read the references outlined above as they will greatly help you in furthering your understanding of what nonces are, when you should use them and how.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.