In WordPress, using hooks allows you to execute custom code before or after specific actions are performed; this can be used to add additional functionality or modify existing functionality. There are two common types of hooks: action hooks and filter hooks.
The following is an example PHP file that demonstrates how to use WordPress hooks to execute SQL query and update operations:
<?php
// 引入 WordPress 核心文件
require_once( dirname( __FILE__ ) . '/wp-load.php' );
// 动作钩子示例
function my_custom_action_hook() {
global $wpdb;
// 执行 SQL 查询
$table_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results( "SELECT * FROM $table_name" );
// 处理结果
foreach ( $results as $row ) {
$result = [];
$result = (array) $row; // 将标准对象转换为数组
// 在此处添加自定义代码
// ...
// 更新数据
$data = array( 'post_title' => 'Hello World' );
$where = array( 'ID' => $result['ID'] );
$wpdb->update( $table_name, $data, $where );
}
}
add_action( 'wp_loaded', 'my_custom_action_hook' );
// 过滤器钩子示例
function my_custom_filter_hook( $content ) {
global $wpdb;
// 执行 SQL 查询
$table_name = $wpdb->prefix . 'posts';
$results = $wpdb->get_results( "SELECT * FROM $table_name" );
// 处理结果
foreach ( $results as $row ) {
$result = [];
$result = (array) $row; // 将标准对象转换为数组
// 在此处添加自定义代码
// ...
// 更新数据
$data = array( 'post_content' => 'New Content' );
$where = array( 'ID' => $result['ID'] );
$wpdb->update( $table_name, $data, $where );
}
return $content;
}
add_filter( 'the_content', 'my_custom_filter_hook' );This example file defines two functions, which are used as callback functions for an action hook and a filter hook, respectively. my_custom_action_hook In this function, an SQL query is executed first, followed by processing the results and updating the data. This function is used. add_action The function adds it to. wp_loaded This hook is executed after WordPress has finished loading.
在 my_custom_filter_hook In this function, an SQL query is also executed and its results are processed; however, the results are now passed as parameters to the function to modify the output content. This function is used add_filter The function adds it to. the_content This hook is executed before WordPress outputs content.