1. 下载wordpress
https://wordpress.org/download/

wget https://wordpress.org/latest.zip
unzip latest.zip -d D:\study\wordpress

 

2. 修改配置文件

cp wp-config-sample.php wp-config.php
/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'root' );

/** MySQL database password */
define( 'DB_PASSWORD', '' );

/** MySQL hostname */
define( 'DB_HOST', '127.0.0.1' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
// ...

 

3. 创建数据库
mysql -uroot -h127.0.0.1 -p

create database wordpress;

 

4. 配置vhost,到网站根目录安装

 

 

5. 创建测试目录 test

wordpress CRUD 数据库操作_.net

6. 创建测试表

CREATE TABLE `test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(64) NOT NULL,
  `mobile` varchar(16) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

wordpress  数据库操作类 ./wp-includes/wp-db.php

下一篇文章: 

wordpress 添加自定义接口

 

查询数据:

-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 17, 2019 at 12:26 PM
-- Server version: 5.7.25-0ubuntu0.16.04.2
-- PHP Version: 7.2.8

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `wordpress4gatsby`
--

-- --------------------------------------------------------

--
-- Table structure for table `wp_term_taxonomy`
--

CREATE TABLE `wp_term_taxonomy` (
  `term_taxonomy_id` bigint(20) UNSIGNED NOT NULL,
  `term_id` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
  `taxonomy` varchar(32) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
  `description` longtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
  `parent` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
  `count` bigint(20) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

--
-- Dumping data for table `wp_term_taxonomy`
--

INSERT INTO `wp_term_taxonomy` (`term_taxonomy_id`, `term_id`, `taxonomy`, `description`, `parent`, `count`) VALUES
(1, 1, 'category', '', 0, 10),
(2, 2, 'category', '新闻图片', 0, 0),
(3, 3, 'post_format', '', 0, 1),
(4, 4, 'category_media', '海报图片', 0, 2),
(5, 5, 'category_media', '文章插图', 0, 1),
(6, 6, 'category_media', '文章封面图', 0, 3);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `wp_term_taxonomy`
--
ALTER TABLE `wp_term_taxonomy`
  ADD PRIMARY KEY (`term_taxonomy_id`),
  ADD UNIQUE KEY `term_id_taxonomy` (`term_id`,`taxonomy`),
  ADD KEY `taxonomy` (`taxonomy`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `wp_term_taxonomy`
--
ALTER TABLE `wp_term_taxonomy`
  MODIFY `term_taxonomy_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

在wp-admin/includes/ajax-actions.php文件中添加函数:

function wp_ajax_category_media_handler() {
    global $wpdb;

    $taxonomy = isset($_GET['taxonomy']) ? $_GET['taxonomy'] : 'category_media';
    $sql = sprintf("SELECT * FROM %s where taxonomy='%s'",
        $wpdb->base_prefix."term_taxonomy", addslashes($taxonomy));
    // echo $sql."\n";
    $rows = $wpdb->get_results($sql);
    wp_send_json_success($rows, 200);
}

wp-admin/admin-ajax.php 在is_user_logged_in前面添加2行:

add_action('wp_ajax_category_media', 'wp_ajax_category_media_handler');
add_action('wp_ajax_nopriv_category_media', 'wp_ajax_category_media_handler');

测试接口 query.php

<?php

function build_query(/* assoc */$a) {
    $m = [];
    array_walk($a, function($item, $key) use (&$m) {
        $m[] = urlencode($key).'='.urlencode($item);
    });
    return implode('&', $m);
}

$ch = curl_init();

$headers = [
    // "Origin: http://172.16.0.224:8087",
    "Referrer: http://172.16.0.224:8087/wp-json/wp/v2/media",
    "X-Requestd-with: XMLHttpRequest",
    "Content-Type: application/x-www-form-urlencoded"
];

$a = array(
    "action" => "category_media",
    "taxonomy" => "category_media",
);

$postdata = build_query($a);
// echo $postdata."\n\n";

array_push($headers, sprintf("Content-Length: %d", strlen($postdata)));

curl_setopt_array($ch, [
    CURLOPT_URL => 'http://172.16.0.224:8087/wp-admin/admin-ajax.php',
    CURLOPT_HEADER => 1,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_POST => 0,
    CURLOPT_BINARYTRANSFER => 1,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => $postdata
]);

$data = curl_exec($ch);
curl_close($ch);

echo $data.PHP_EOL;

php query.php

HTTP/1.1 200 OK
Date: Mon, 17 Jun 2019 10:30:19 GMT
Server: Apache/2.4.34 (Unix) OpenSSL/1.0.2o PHP/7.2.8 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/7.2.8
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Robots-Tag: noindex
X-Content-Type-Options: nosniff
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
X-Frame-Options: SAMEORIGIN
Referrer-Policy: strict-origin-when-cross-origin
Content-Length: 430
Content-Type: application/json; charset=UTF-8

{"success":true,"data":[{"term_taxonomy_id":"4","term_id":"4","taxonomy":"category_media","description":"\u6d77\u62a5\u56fe\u7247","parent":"0","count":"2"},{"term_taxonomy_id":"5","term_id":"5","taxonomy":"category_media","description":"\u6587\u7ae0\u63d2\u56fe","parent":"0","count":"1"},{"term_taxonomy_id":"6","term_id":"6","taxonomy":"category_media","description":"\u6587\u7ae0\u5c01\u9762\u56fe","parent":"0","count":"3"}]}
 

 

* MockValue.php

<?php
/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 5/24/2019
 * Time: 11:55 AM
 */

class MockValue {
    public static $letters = "abcdefghijklmnopqrstuvwxyz";
    public static $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static $numeric = "0123456789";

    public static $email_suffix =
        ["@gmail.com", "@yahoo.com", "@msn.com", "@hotmail.com", "@aol.com", "@ask.com",
            "@live.com", "@qq.com", "@0355.net", "@163.com", "@163.net",
            "@263.net", "@3721.net", "@yeah.net", "@126.com", "@sina.com", "@sohu.com", "@yahoo.com.cn"];
    public static $mobile_prefix = ["134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "158", "159", "130",
        "131", "132", "155", "156", "133", "153"];
    public static $grade = ['高三','高二','高一','初三','初二','初一','小六','六年级','七年级','八年级','九年级','高中','初中','小学'];

    public static $gradeValue = ["03-2016", "03-2017", "03-2018", "02-2016", "02-2017", "02-2018", "02-2015", "02-2016", "02-2017", "02-2018", "01-2013"];

    public static function getNumber(/* int */$width) /* int */ {
        $min = 1;
        if ($width <= 1) {
            $width = 1;
            return rand(0, 9);
        }
        $width -= 1;
        for ($i = 0; $i <$width; $i++) {
            $min *= 10;
        }
        $max = $min * 10 - 1;
        return rand($min, $max);
    }

    public static function genPassword() {
        return self::random(rand(5,10), self::$letters.self::$numeric);
    }

    public static function getMobile() {
        return self::random(1, self::$mobile_prefix) . self::random(8, self::$numeric);
    }

    public static function getGrade() {
        return self::random(1, self::$grade);
    }

    public static function getGradeValue() {
        return self::pick(self::$gradeValue);
    }

    public static function getElement($list) {
        if (is_string($list)) {
            $n = strlen($list);
        } else if (is_array($list)) {
            $n = count($list);
        } else {
            throw new InvalidArgumentException("list must string or array");
        }
        return $list[rand(0, $n-1)];
    }

    public static function getName() {
        return self::random(8, self::$letters);
    }

    public static function getNumStr($len) {
        return self::random($len, self::$numeric);
    }

    public static function getIP() {
        return sprintf("%d.%d.%d.%d", rand(1,254), rand(1,254), rand(1,254), rand(1,254));
    }

    private static function random(/*int */$length, /* ArrayAccess */ $list) {
        if ($length <= 1) {
            $length = 1;
        }
        $s = "";
        if (is_string($list)) {
            $n = strlen($list);
        } else if (is_array($list)) {
            $n = count($list);
        } else {
            throw new InvalidArgumentException("list must string or array");
        }

        while ($length--) {
            $s .= $list[ rand(0, $n-1) ];  // inclusive $n-1
        }
        return $s;
    }

    public static function pick($list) {
        $n = count($list);
        if ($n < 1) {
            throw new RunTimeException("Empty list");
        }
        return $list[ rand(0, $n-1) ];
    }

    public static function getHD() {
        $op = self::$letters. self::$upper. self::$numeric;
        return self::random(22, $op)."==";
    }


}

* insert.php

<?php

define('__ROOT__', dirname(dirname(__FILE__)));
include __ROOT__ . '/wp-blog-header.php';
include __ROOT__ .'/test/lib/MockValue.php';

/**@var \wpdb */
global $wpdb;

$n = 20;
while ($n-- > 0) {
    $ra = $wpdb->insert("test_table", [
        'username' => MockValue::getName(),
        'mobile' => MockValue::getMobile(),
        'created_at' => date('Y-m-d H:i:s', time()),
        'updated_at' => date('Y-m-d H:i:s', time()),
    ]);
    echo $ra.'<br />';
    sleep(1);
}

* update.php

<?php

define('__ROOT__', dirname(dirname(__FILE__)));
include __ROOT__ . '/wp-blog-header.php';

/**@var \wpdb */
global $wpdb;

$data = array(
    'username' => 'python'
);

$where = array(
    'id' => 2,
);

$ret = $wpdb->update("test_table", $data, $where);
var_dump($ret);

* delete.php

<?php

define('__ROOT__', dirname(dirname(__FILE__)));
include __ROOT__ . '/wp-blog-header.php';

/**@var \wpdb */
global $wpdb;

// $ret = $wpdb->delete('test_table', array('id' => 21));

$sql = "select username, mobile from test_table";
$results = $wpdb->get_results($sql, 'OBJECT');

// echo '<pre>';
// var_dump($results);
echo json_encode($results);