Wordpress 检查slug是否存在,否则在woocommerce中创建新产品
我在下面有一个代码,它将把产品插入woocommerce中的数据库:Wordpress 检查slug是否存在,否则在woocommerce中创建新产品,wordpress,woocommerce,Wordpress,Woocommerce,我在下面有一个代码,它将把产品插入woocommerce中的数据库: $post = array( 'post_author' => $user_id, 'post_content' => '', 'post_status' => "publish", 'post_title' => $product->part_num, 'post_parent' => '', 'post_type' => "product", ); $po
$post = array(
'post_author' => $user_id,
'post_content' => '',
'post_status' => "publish",
'post_title' => $product->part_num,
'post_parent' => '',
'post_type' => "product",
);
$post_id = wp_insert_post( $post, $wp_error );
但是,在插入新产品之前,我想检查数据库中是否存在slug,否则,我想添加一个新的slug并在slug上附加一个数字
输入示例:
$new_url = sanitize_title('This Long Title is what My Post or Page might be');
输出:
这个长标题可能就是我的文章或页面
现在,我想检查这个slug是否已经存在于数据库中。如果它存在,我将在slug上附加一个数字(就像wordpress permalink所做的那样)。如果它已经存在,我想将其输出为:
这个长标题是“我的帖子”或“可能是”页面
我想将新产品与此新slug一起添加到数据库中。
有人知道吗?没有经过测试,只是编写了代码。试试这个,让我知道
function slug_exists($slug){
if(get_page_by_path( $slug, OBJECT, 'product' )){
return true;
}
return false;
}
$slug = 'your_slug';
$new_slug = $slug;
$c=1;
while(slug_exists($new_slug)){
$new_slug = $slug.'-'.$c;
$c++;
}
//$new_slug包含所需的slug内部参数的用途:函数slug_exists($slug){