WordPress 的數據庫採用了 mysql 數據庫,同時 WordPress 也很好的封裝了數據庫的使用函數,從而讓開發者們能很好的應用 WordPress 的數據庫函數進行主題或者插件開發。
WordPress 數據庫的封裝類位於 /wp-includes/wp-db.php,wp-db.php 包含了數據庫操作的具體説明,該類對象實例化的參數為 $wpdb,我們可以在模板文件中直接使用,或者在 function 使用 global 來使其成為全局變量。
本文將列舉幾個常見的數據庫操作函數:

  • insert($table, $data, $format) — 在指定的表中插入一條數據。
  • update($table, $data, $where, $format, $where_format) — 在指定的表中更新一條數據
  • get_var( $query = null, $x = 0, $y = 0 ) – 查詢指定單個字段數據
  • query($query) — SQL 語句查詢
  • get_results($query, $output) — 返回搜索結果
  • escape($data) — 對插件數據庫中的數據進行轉義,使用了 addslashes() 函數
  • prepare( $query, $args = null ) – 預處理 SQL 查詢語句, 使用 php 的 sprintf() 來格式化字符串。
  • set_prefix($prefix) — 設置數據表前綴
  • prepare($query) — safely prepares an SQL query for execution with sprintf()-like syntax.
  • get_row($query, $output, $y) — 查詢指定行的數據,$y 默認為 0 。
  • get_col($query, $x) — 查詢指定列的數據,$x 默認為 0

應用實例:
1 、插入數據

/**
 * insert
 */
$wpdb->insert( $wpdb->posts, array( 'post_title' => $mytitle ) );
$wpdb->insert( $wpdb->options, array(
            'option_name',
            'new_option_key',
            'option_value' => 'New Option Value',
            'autoload' => 'yes' )
            );

2 、更新數據

/**
 * update
 */
$wpdb->update( $wpdb->posts, array( 'post_title' => $mytitle ),
            array( 'ID' => $myid )
            );
$wpdb->update( $wpdb->options,
            array( 'option_value' => 'New Option Value' ),
            array( 'option_name' => 'new_option_value' )
            );

3 、查詢指定單個字段數據

/**
 * get_var
 */
$post_id = $wpdb->get_var(
            $wpdb->prepare( "SELECT post_id FROM
                    $wpdb->postmeta WHERE
                    post_id = %d AND
                    meta_key = 'enclosure' AND
                    meta_value LIKE (%s)", $post_ID, $url . '&' )
            );
$content = $wpdb->get_var(
            $wpdb->prepare("SELECT post_content FROM " .
                    "$wpdb->posts WHERE " .
                    "post_title = %s AND " .
                    "ID = %d", $title, $id )
        );

4 、執行 sql 語句,常用於刪除與更新

/**
 * query
 */
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
$wpdb->query( "UPDATE $wpdb->posts SET post_title = '$mytitle' WHERE ID = $myid" );

5 、轉義數據

/**
 * query and escape
 */
$mytitle = $wpdb->escape( $mytitle );
$myid    = absint( $myid );
$wpdb->query( "UPDATE $wpdb->posts SET post_title = '$mytitle' WHERE ID = $myid" );

6 、返回查詢結果集

/**
 * get_results
 */
$type = $wpdb->get_results( "SELECT post_type FROM " .
                "$wpdb->posts WHERE ID=$id" );