How to use $wpdb variable in wordpress

Asked

Viewed 595 times

0

I have this code in a php file inside the wordpress installation, does not work I do not know what is wrong.

global $wpdb;

$tableName = "wp_posts";

$result = $wpdb->get_results("SELECT * FROM $tableName");

foreach ($result as $row) {

echo '<p>' .$row->coluna_teste. '</p>';
  • Are you with exactly these parameters? because really everything is wrong that way

1 answer

2


$wpdb::get_results() returns a list of objects by default, where each property is a column. The table wp_posts doesn’t have a column coluna_teste, therefore the mistake.

The code below is correct and will bring the titles:

global $wpdb;

// Para tabelas padrãdo do WP Use $wpdb->nomedatabela para buscar o nome 
// já com o prefixo, que pode não ser o mesmo em todos os ambientes
$result = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} LIMIT 10" );

foreach ( $result as $row ) {
    echo '<p>' . $row->post_title . '</p>';
}

Complete documentation of the class $wpdb

PS: The result of this query is the same as get_posts(). Using the function is preferable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.