9951 explained code solutions for 126 technologies


php-wordpressHow to run an SQL query in WordPress using PHP?


To run an SQL query in WordPress using PHP, you can use the $wpdb global object. This object provides a set of methods to interact with the WordPress database.

For example, to run a simple SELECT query:

$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}posts" );

This will return an array of objects containing the results of the query.

Code explanation

  • $wpdb: This is the global object that provides access to the WordPress database.
  • get_results(): This is a method of the $wpdb object that is used to run a SELECT query.
  • $wpdb->prefix: This is a property of the $wpdb object that contains the table prefix for the WordPress database.

Helpful links

Edit this code on GitHub