在 wordpress 中插入新帖子时触发操作 [英] Trigger action when new post is insert in wordpress
问题描述
我的问题是,
在数据库中插入新帖子时,是否有任何过滤器或操作会触发..?
Is there any filter or action that trigger when new post is insert in database..?
这背后的原因是当从管理端插入新帖子时,我想在帖子元数据中添加密钥.
The reason behind it is I want to add key in post meta when new post is insert from admin side.
我有一个名为 "save_post"
的操作,但在参考 link 之后a> .此操作在创建和更新帖子中触发.但我只想在创建帖子时添加元键而不是在更新时
I got Action called "save_post"
but after refer link .This action trigger in created and update post.
but I only want to add meta key when post is created not at update time
推荐答案
您可以使用 wp_insert_post
这样您就可以在插入帖子后立即获得 post_id
,然后您可以使用它来添加 meta_key
.
You can use wp_insert_post
so you will get post_id
as soon as post inserted and you can then use that to add meta_key
.
如果您不使用 wp_insert_post
并且想使用 action
那么您可以简单地输入以下代码:
If you are not using wp_insert_post
and want to use action
then you can simply put below code :
if ( wp_is_post_revision( $post_id ) )
return;
这意味着如果您正在更新帖子,那么它将从 function
返回.
which means that if you are updating the post, then it will return back from function
.
已编辑
方法 1 来实现它.
您可以简单地使用 get_post
方法检查 post 是否存在.如下所示:
You can simply check with the get_post
method that post is there or not.something like below:
add_action('save_post', 'check_for_post_in_database');
function check_for_post_in_database($post_id) {
//check if the post is in the database or not with get_post( $post_id ) == null
if( get_post( $post_id ) == null ) {
//your code to add meta
}
}
//You can do same thing with publish_post
方法 2 来实现它.
add_action('publish_post', 'check_for_meta_in_database');
function check_for_meta_in_database($post_id) {
global $wpdb;
$your_meta = get_post_meta($post_id, 'meta_key', true);
if( empty( $your_meta ) && ! wp_is_post_revision( $post_id ) ) {
update_post_meta($post_id, 'meta_key', 'meta_value');
}
}
但是正如你所说的有很多元,这个方法会有点长.
But as you said there are many meta there, this method will be bit long.
方法 3 来实现它.
你可以按照 rnevius 的建议去做,这也是我会选择的.就像:
You can do as rnevius suggested which is the one even I would opt. Its like :
add_action( 'transition_post_status', 'check_transition_and_then_add_meta', 10, 3 );
function check_transition_and_then_add_meta( $new_status, $old_status, $post ) {
if ( ( 'draft' === $old_status || 'auto-draft' === $old_status ) && $new_status === 'publish' ) {
add_post_meta($post->ID, 'your_meta_key', 'your_meta_value');
}
}
或者你可以用 draft_to_publish
来做,比如:
or else you can do it with draft_to_publish
like:
//as rnevius suggested {$old_status}_to_{$new_status}
add_action( 'draft_to_publish', 'add_meta_when_status_change' );
function add_meta_when_status_change() {
add_post_meta($post->ID, 'your_meta_key', 'your_meta_value');
}
您可以参考 codex 了解有关后期过渡的更多信息.
You can refer codex for more information about post transition.
这篇关于在 wordpress 中插入新帖子时触发操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!