Hongmu Notes
Home Program Notes WordPress Hook: Create a new PHP file and then execute SQL query and update operations.
Program Notes wordpress

WordPress Hook: Create a new PHP file and then execute SQL query and update operations.

WordPress Hook: Create a new PHP file and then execute SQL query and update operations.

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.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

What should I do if the Redis Object Cache plug-in cannot be linked after wordpress redis changes the password?

What should I do if the Redis Object Cache plug-in cannot be linked after wordpress redis changes the password? Program Notes wordpress

Problem description: My wordpress site server uses pagoda panel, installed php8.0, and installed redis on the extension panel, and installed Redis Object Cache plug-in in wordpress. In fact, in general, you don't need to do anything, just start it directly. However, it is unsafe for radis not to set a password, which is a risky loophole, so I still think it is better to set a password, …
👁 256
How do I disable revisions and automatic draft saving in WordPress?

How do I disable revisions and automatic draft saving in WordPress? Program Notes wordpress

WordPress's automatic article revision tracking feature logs every time you edit an article in the后台; each revision is recorded as a separate entry in the `wp_posts` table. Due to the interplay between article revisions and automatic saving, the article ID often grows larger over time. While this typically does not cause significant issues for your WordPress installation, an excessive number of article versions can place a considerable burden on your storage space and database...
👁 373
Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress

Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress Program Notes wordpress

PS1: Second revision – now supports data transfer between categories, posts, and tags. PS2: If the post IDs consistently don't match, you can try clearing the WordPress post category data table and relationship tables. I previously used Typecho for my blog, but later migrated to Empire; however, Empire has too many features – using it for a blog feels like putting a large hammer into a small hole! Additionally, I often record important code snippets in my blog – all of which I've painstakingly written...
👁 546
WordPress issue: pages freezing due to image transcoding

WordPress issue: pages freezing due to image transcoding Program Notes wordpress

Last night, while uploading an image, for some reason, the uploaded image was automatically transcoded. Transcoding type: BASE64 encoding. For an image on a website, simply upload it to your server and then access the link – the image will then be displayed. However, there is another approach: directly transcoding the image; then you can simply access the converted image using its encoded URL. Problem description: When an image is relatively small (e.g., only a few KB in size), transcoding it and then hosting it on a website can help avoid...
👁 152
WordPress database query operations

WordPress database query operations Program Notes wordpress

To connect to a database for a WordPress installation, you need to include the `wp-config.php` file in your PHP script. This file contains the database configuration details for WordPress installation and other constants. Here is a simple example demonstrating how to include the `wp-config.php` file and establish a database connection: // Include the wp-config.php file: require...
👁 378
WordPress MySQL Database Table and Subtable Structure Functionality Guide

WordPress MySQL Database Table and Subtable Structure Functionality Guide Program Notes wordpress

WordPress uses a MySQL database. Its data table structure differs slightly from that of conventional databases; data can be stored either in the form of standard data tables or as data elements – the latter approach is less intuitive when viewed directly. To become a developer, you must understand the basic structure of the WordPress database and be able to use it within your own plugins or themes to write to or read from the database. I. Data Tables – As of WordPress...
👁 374

Recommended reading

(Adaptive mobile version) Gift Box PBootCMS Website Template – Download Website Source Code for Packaging Boxes – 0789

(Adaptive mobile version) Gift Box PBootCMS Website Template – Download Website Source Code for Packaging Boxes – 0789 Practical Collection pbootcms Template

A gift box and packaging box PbootCMS website template, compatible with both PC and WAP devices. Featuring an elegant and premium design style, this template is ideal for showcasing gift designs, custom packaging solutions, and brand case studies. It enables packaging design companies to display their product craftsmanship online and attract corporate clients. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 41
Using ChatGPT with the official API to generate articles – PHP Tutorial

Using ChatGPT with the official API to generate articles – PHP Tutorial Language Notes PHP

I heard this tool is really popular and awesome – many webmasters have started using it to generate articles or build websites. So, I wrote a simple PHP script that integrates with the official API; it's quite straightforward: just use Composer to install the required package and then simply make calls to the API. I tested it out – with just one API key, you can generate 900 articles, and the quality is quite good. For the API call tutorial, head over to this link to find a PHP package; after looking through several options, I chose this one: ope...
👁 163
Electronic components foreign trade responsive English website template 0488

Electronic components foreign trade responsive English website template 0488 Practical Collection Yiyou template

This EyouCMS responsive English-language website template is ideal for the electronic components export industry. Its modern, international design style effectively showcases electronic component products, technical specifications, export advantages, and global market presence, helping electronics companies enhance their brand visibility in the international market. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 45
(Adaptive mobile version) Domestic service company PBootCMS website template; Parenting, cleaning and nanny service website source code download – 0790

(Adaptive mobile version) Domestic service company PBootCMS website template; Parenting, cleaning and nanny service website source code download – 0790 Practical Collection pbootcms Template

A PbootCMS website template designed for domestic service companies and childcare/housekeeping services, compatible with both PC and WAP devices. Its cozy yet professional design is ideal for showcasing services such as postpartum care specialists, childcare providers, and domestic helpers. This template helps domestic service providers build a professional online presence and attract new parents and families. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 59
Responsive premium flower bouquet gift website template – 0489

Responsive premium flower bouquet gift website template – 0489 Practical Collection Yiyou template

An eyoucms responsive website template for exquisite bouquets and flower gifts. The design style is fresh and beautiful, and can display flower bouquet products, gift designs, brand stories and delivery services. It helps flower brands display their products online and attract individual and corporate customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Summary of common problems in Yiyou CMS installation...
👁 52
(PC+WAP) Property Management Website Template – Download PbootCMS Property Management & Security Website Source Code – 0791

(PC+WAP) Property Management Website Template – Download PbootCMS Property Management & Security Website Source Code – 0791 Practical Collection pbootcms Template

A PbootCMS website template specifically designed for property management and security service providers, compatible with both PC and WAP mobile devices. Its professional and sophisticated design effectively showcases property management services, security solutions, and company credentials. This template helps property management firms build a strong online brand presence, enhance customer trust, and expand their business reach. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: ad...
👁 45