我有一个自定义文件名为xxxx_url
. xxxx_url
应该是唯一的。
所以,在发表这篇文章之前,我想确保xxxx_url
是否唯一?如果不是唯一的,则应拒绝发布帖子。
我试过了publish_post
. 但这不是正确的,因为当我们发布帖子时,它会触发。我想在发布之前运行我的代码。
我有一个自定义文件名为xxxx_url
. xxxx_url
应该是唯一的。
所以,在发表这篇文章之前,我想确保xxxx_url
是否唯一?如果不是唯一的,则应拒绝发布帖子。
我试过了publish_post
. 但这不是正确的,因为当我们发布帖子时,它会触发。我想在发布之前运行我的代码。
在开始wp_insert_post
, 保存/更新帖子的功能,有一个名为wp_insert_post_empty_content
. 默认情况下,此筛选器检查标题、编辑器和摘录字段是否全部为空,在这种情况下,保存过程将暂停。
但是,由于要保存的所有字段都传递给此筛选器,因此可以扩展此筛选器以包括任何其他测试,以确定是否应将帖子视为空。应该是这样的:
add_filter (\'wp_insert_post_empty_content\',\'wpse312975_check_unique_url\',10,2);
function wpse312975_check_unique_url ($maybe_empty, $postarr) {
// extract custom field from $postarr, check uniqueness
if ($unique) return false else return true;
}
注意:函数必须返回“true”才能停止保存过程。如果自定义字段不唯一,您可能还需要回显警告。
我会wp_insert_post_data 过滤并尽可能少地处理这一问题,因为据我所知,您不想阻止帖子的插入,只想避免发布具有重复元值的帖子。
在这种情况下,我不能浪费太多时间,因为您没有共享任何代码,但这里有一些过滤器的伪代码可以工作:
function wp8193131_check_if_meta_value_is_unique ( $data, $postarr ) {
// setup an uniqueness flag.
$meta_is_unique = true;
// check if the meta is unique and modify the `$meta_is_unique` flag accordingly.
// {...} <- your code
// if the meta is NOT unique keep the post status in draft.
if ( ! $meta_is_unique ) {
// you can force the current post to be draft until the meta value will became unique.
$data[\'post_status\'] = \'draft\';
// maybe, update the meta value with a hint of the fact that it\'s not unique.
// or display a dashboard notice about it.
}
return $data;
}
add_filter( \'wp_insert_post_data\', \'wp8193131_check_if_meta_value_is_unique\' );
这个过滤器的另一个优点是它与附件分离wp_insert_attachment_data
.我希望这有帮助,无论你做什么,听起来都很棒!
在提交文章进行发布之前,使用AJAX检查其唯一性如何?
$( \'#post\' ).on( \'submit\', function( event ) {
event.preventDefault(); // Prevent publishing
//Now do some AJAX Checks
$.post( ajaxurl, data, function(response) {
if ( response === \'success\' ) {
$( this ).off( event ).submit();
} else {
alert( \'The custom field must be unique\' );
}
});
});
虽然代码没有经过测试,但应该可以工作。您可能需要使用它来获得所需的结果。支票应转到wp_insert_post
. 每当发布或编辑帖子时,就会触发此挂钩。
在那里,您可以进行自定义查询以检查是否有任何帖子已经具有相同的内容xxxx_url
值或否。
add_action(\'wp_insert_post\', function($post_id) {
$meta_key = \'xxxx_url\';
$meta_value = get_post_meta($post_id, $meta_key, true);
$query = new WP_Query([
\'post_type\' => get_post_type($post_id), // This might be unnecessary, if you check `post` post type only. Or use `any`.
\'meta_query\' => [
[
\'meta_key\' => $meta_key,
\'meta_value\' => $meta_value,
]
]
]);
if ($query->have_posts()) {
// invalid key, post with the same value already exists
} else {
// valid, key was not found anywhere
}
});
假设我有一个主题选项或自定义的postmeta文本区域。现在我想执行多个短代码、一般文本、图像等。最佳实践是什么?为什么?选项1:$content = //my text area data; echo apply_filters(\'the_content\', $content); 选项2:$content = //my text area data; echo do_shortcode($content); 请告诉我哪一个是最佳实践,以及为什么。EDIT让我详细描