Home >CMS Tutorial >WordPress >How to use wordpress hook function to add a record while publishing an article

How to use wordpress hook function to add a record while publishing an article

藏色散人
藏色散人Original
2020-01-02 09:30:382499browse

How to use wordpress hook function to add a record while publishing an article

#How to use WordPress hook function to add a record while publishing an article?

This article will introduce how to use the WordPress hook function to add a record to the voting table while publishing an article. The following is the specific implementation, don’t miss it

Recommendation: 《WordPress Tutorial

I want to sort the articles according to the number of votes. Those who have voted will have their votes recorded, while articles without votes will not. Record, the default vote is 0. At this time, there is a problem with sorting. It sorts the articles with records first, because the votes may be negative. After the negative numbers are sorted, the articles without voting records will be sorted. At this time, there will be articles without votes. Articles with 0 votes are ranked after negative numbers, as shown in the picture:

How to use wordpress hook function to add a record while publishing an article

How to use wordpress hook function to add a record while publishing an article

Voting record table

Generated sql statement:

SELECT wp_posts.ID FROM wp_posts LEFT JOIN wp_wti_like_post on wp_wti_like_post.post_id=wp_posts.ID WHERE 1=1 AND ( ( post_date_gmt > ’2013-11-16 12:17:03′ ) ) AND wp_posts.post_type = ‘post’ AND (wp_posts.post_status = ‘publish’ OR wp_posts.post_status = ‘private’) ORDER BY wp_wti_like_post.value DESC,wp_posts.post_date DESC LIMIT 5, 5

How should the sql statement be written?

Solution:

Isn’t it enough to use WordPress’s hook function to add a record to the voting table while publishing the article?

Add the code directly:

The code is as follows:

//发表文章的同时插入数据到喜欢表
function new_article($post_ID){ global $wpdb; $ip = WtiGetRealIpAddress(); $query = "INSERT INTO {$wpdb->prefix}wti_like_post SET "; $query .= "post_id = '" . $post_ID . "', "; $query .= "value = '0', "; $query .= "date_time = '" . date('Y-m-d H:i:s') . "', "; $query .= "ip = '$ip'"; $success = $wpdb->query($query); if($success){ return $post_ID; }}add_action('publish_post', 'new_article');

Put this code into the theme function.php.

The above is the detailed content of How to use wordpress hook function to add a record while publishing an article. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn