我想在用户发帖之前检查一个条件。用户必须有一个jeton (用户元数据),如果没有,帖子将不会被推送到数据库中,否则,它将有一个jeton将被烧毁。我要找的钩子或过滤器是什么?
/* Jeton is French for token or coin */
add_action('what_is_the_action_or_filter_im_looking_for', 'check_jeton_before_publish');
function check_jeton_before_publish($data) {
$user_id = get_current_user_id(); // Get user ID
$meta_jeton = get_user_meta($user_id, 'jeton'); // Jeton count
if ($meta_jeton == 0 || empty($meta_jeton)) { // No jeton ? No post !
return;
} else { // Jeton ? Post, then burn one jeton
$new_jeton_count = $meta_jeton - 1;
update_user_meta($user_id, 'jeton', $new_jeton_count);
return $data;
}
}
感谢您的宝贵时间!
发布于 2019-11-08 04:56:56
根据wp_post_insert的说法,filter wp_insert_post_empty_content应该可以为您工作。
/**
* Filters whether the post should be considered "empty".
*
* The post is considered "empty" if both:
* 1. The post type supports the title, editor, and excerpt fields
* 2. The title, editor, and excerpt fields are all empty
*
* Returning a truthy value to the filter will effectively short-circuit
* the new post being inserted, returning 0. If $wp_error is true, a WP_Error
* will be returned instead.
*
* @since 3.3.0
*
* @param bool $maybe_empty Whether the post should be considered "empty".
* @param array $postarr Array of post data.
*/
if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
if ( $wp_error ) {
return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
} else {
return 0;
}
}
您可以在wp_insert_post_empty_content筛选器中执行条件,并返回true以停止插入帖子。
发布于 2019-11-08 16:00:06
我认为@KGreene的答案值得一试,谢谢你的投入。
我改变了我的策略,如果用户没有jeton,我会重定向他们,这样他们甚至看不到编辑器,并在发布时在不同的钩子中烧掉jeton。
/*
* Redirect user that doesnt have jeton, let others proceed
* https://developer.wordpress.org/reference/hooks/save_post/
*/
function handle_before_publish_post($post_id, $post, $update) {
// Only on post creation not update (they can update with 0 jeton)
if ($update) {
return;
}
$poster_id = $post->post_author;
$meta_jeton = get_user_meta($poster_id, 'jeton')[0];
if ($meta_jeton > 0) {
return;
} else {
wp_redirect('[my-domain]/wp-admin/edit.php?post_type=[my-custom-post-type]');
}
}
add_action('save_post_[my-custom-post-type]', 'handle_before_publish_post', 10, 3);
/*
* Use a jeton on post creation
* https://developer.wordpress.org/reference/hooks/new_status_post-post_type/
*/
function handle_after_publish_post($post_id, $post) {
// Burn jeton
$poster_id = $post->post_author;
$meta_jeton = get_user_meta($poster_id, 'jeton')[0];
$new_jeton_count = $meta_jeton - 1;
update_user_meta($poster_id, 'jeton', $new_jeton_count);
return;
}
add_action('publish_[my-custom-post-type]', 'handle_after_publish_post', 10, 3);
这不是我想要的方式,但它工作得很好。
感谢大家抽出时间来
https://stackoverflow.com/questions/58750980
复制相似问题