阻止相同的WordPress帖子标题

时间:2014-04-16 作者:danyo

我正在wordpress网站上工作,用户可以在那里提交自己的帖子。我想阻止用户添加具有相同内容的帖子post_title

这是我当前检查帖子标题是否存在的方式:

$posts = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = \'post\' AND post_status = \'publish\' OR post_status = \'trash\' OR post_status = \'draft\'");
从表单中获取帖子标题

$alias = $_POST[\'post_title\'];
检查post\\u title是否为空(如果为创建随机post\\u title),否则使用用户定义的post\\u title

if ($_POST[\'post_title\'] == \'\'){
    $alias = generateRandomString();
} else {
    $alias = $_POST[\'post_title\'];
}
然后检查post\\u标题是否已经存在,如下所示:

if (in_array($alias, $items)){
    echo \'<p style="color:#fff">Sorry, That Title already exists!</p>\';
} else {
//insert the post
}
我的问题是,如果帖子标题已经存在,wordpress会在其后面添加一个数字。有没有办法阻止wordpress这样做?

上述结果表明:

Array ( [0] => db [1] => abi [2] => ybd [3] => cc [4] => cc-2 [5] => fb )
我需要防止cc-2发生。

1 个回复
SO网友:codearachnid

我最近遇到了一个类似的问题(而是解决如何重置导入后脏的段塞)。这是我用来重置Slug的代码片段:

$wpdb->update( 
    $wpdb->posts, 
    array( \'post_name\' => sanitize_title( $post_to_fix->post_title ) ), 
    array( \'ID\' => $post_to_fix->ID ), 
    array( \'%s\' ), 
    array( \'%d\' ) 
);
主要关注sanitize_title, 它在其中清理帖子标题,然后保存到post\\u名称。我相信在你的情况下,如果你对post\\u名称而不是标题进行查询,你将有更好的机会处理标题中的细微差别,并提供准确的匹配。因此,这里粗略介绍一下您可能会在插入后检查/添加逻辑中添加的内容:

// check & set from a valid $_POST property or random string for a post name
$post_name = !empty($_POST[\'post_title\']) ? generateRandomString() : $_POST[\'post_title\'];

// filter by post type, note it can also take an array of post types
$post_type = \'post\'; 

$get_post_args = array(
    \'name\' => $post_name,
    \'post_type\' => $post_type, 
    \'post_status\' => \'any\',
    // get all posts
    \'posts_per_page\' => -1,
    // improve the performance of your query
    \'fields\' => \'ids\',
    \'no_found_rows\' => true,
    \'update_post_term_cache\' => false,
    \'update_post_meta_cache\' => false
    );

$dup_posts_check = new WP_Query( $get_post_args );

if( !empty($dup_posts_check) ){
    echo \'<p style="color:#fff">Sorry, That Title already exists!</p>\';
} else {
    //insert the post
}

结束

相关推荐

Sanitize slug title

我需要将此字符串转换为帖子url:(带点和欧元符号的数字)例如:9000欧元->9000欧元我找到了此函数,但不起作用:add_filter( \'sanitize_title\', \'sanitize_title_extra\' ); function sanitize_title_extra( $title ) { $friendlyURL = htmlentities($title, ENT_COMPAT, \"UTF-8\", false); &