WordPress: Access Database From Widget Code

2019-07-26 05:27发布

How can I access to my WordPress database and run SQL from the widget code? (I need to access to the settings of one of my plugins from the widget code)

3条回答
劳资没心,怎么记你
2楼-- · 2019-07-26 06:03

You can check this http://codex.wordpress.org/Class_Reference/wpdb for full documentation. In resume you can do something like the follow from any part of your widget code:

global $wpdb;
$rows = $wpdb->get_results( "SELECT id, name FROM table" );
查看更多
Deceive 欺骗
3楼-- · 2019-07-26 06:12

just include wp-blog-header.php in the file

require('yourpath/wp-blog-header.php');

global $wpdb;

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

var_dump($result);
查看更多
乱世女痞
4楼-- · 2019-07-26 06:13

If you want to retrieve some information from the database, you can use one of four helper functions to query the database and retrieve the data.

get_results():

This is the function that we looked at earlier. It is best for when you need two-dimensional data (multiple rows and columns). It converts the data into an array that contains separate objects for each row.

get_row():

When you need to find only one particular row in the database (for example, the post with the most comments), you can use get_row(). It pulls the data into a one-dimensional object.

get_col():

This method is much the same as get_row(), but instead of grabbing a single row of results, it gets a single column. This is helpful if you would like to retrieve the IDs of only the top 10 most commented posts. Like get_row(), it stores your results in a one-dimensional object.

get_var():

In many cases, you will need only one value from the database; for example, the email address of one of your users. In this case, you can use get_var to retrieve it as a simple value. The value’s data type will be the same as its type in the database

An example:

<?php
$drafts = $wpdb->get_results("SELECT ID, post_title FROM wp_posts WHERE post_status = 'draft' AND post_author = 5");
foreach ( $drafts as $draft ){
    echo $draft->post_title;
}
?>

Documentation: http://codex.wordpress.org/Class_Reference/wpdb

Source: http://wp.smashingmagazine.com/?p=98071

Hope this helps.

查看更多
登录 后发表回答