我正在建立一个电话号码目录网站。使用wp_insert_post()
访客无需注册或登录即可添加电话号码。有一种称为“数字”的自定义帖子类型,电话号码存储在自定义帖子的元值中。代码如下:
$post_id = wp_insert_post(array (
\'post_type\' => \'numbers\',
\'post_title\' => $name,
\'post_content\' => $details,
\'post_status\' => \'draft\',
\'tax_input\' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, \'number\', $number);
}
我不希望我的用户添加之前已经添加的数字。我需要以某种方式检查输入的电话号码是否已经存在于任何帖子的元值中。
若数据库中已经存在该编号,则不允许用户添加该编号。
最合适的回答,由SO网友:AddWeb Solution Pvt Ltd 整理而成
尝试以下代码。
$args = array(
\'fields\' => \'ids\',
\'post_type\' => \'numbers\',
\'meta_query\' => array(
array(
\'key\' => \'number\',
\'value\' => $number
)
)
);
$my_query = new WP_Query( $args );
if( empty($my_query->have_posts()) ) {
$post_id = wp_insert_post(array (
\'post_type\' => \'numbers\',
\'post_title\' => $name,
\'post_content\' => $details,
\'post_status\' => \'draft\',
\'tax_input\' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, \'number\', $number);
}
}
如果Posteta中有相同的数字,则不允许创建post和post meta。
希望这对你有帮助。
SO网友:Sofiane Achouba
嗨,你可以这样做:
$post_id = wp_insert_post(array (
\'post_type\' => \'numbers\',
\'post_title\' => $name,
\'post_content\' => $details,
\'post_status\' => \'draft\',
\'tax_input\' => $custom_tax,
));
if ($post_id) {
$args = array(
\'post_type\' => \'numbers\',
\'meta_query\' => array(
array(
\'key\' => \'number\',
\'value\' => $number
)
),
\'fields\' => \'ids\'
);
// perform the query
$number_query = new WP_Query( $args );
$number_ids = $number_query->posts;
// add number if the meta-key-value-pair does not exist in another post
if ( empty( $number_ids ) ) {
add_post_meta($post_id, \'number\', $number);
}
}