首页 > 解决方案 > WordPress在发布之前检查帖子标题是否存在并重定向到最旧的帖子而不是创建新帖子

问题描述

我正在使用用户提交的帖子插件,以便让客人在我的 WordPress 网站上发帖。

我希望能够确定用户编写的标题是否已经可用并将用户重定向到现有帖子而不是创建新帖子或重定向和删除新创建的帖子。我试图创建一些应该可以工作的代码,但我不确定我应该将代码放在哪里以便在创建帖子之前捕获标题。如果有帮助,这是我的网站www.epic-review.com

function implode_all($glue, $arr) {
    for ($i=0; $i<count($arr); $i++) {
        if (@is_array($arr[$i])) 
            $arr[$i] = implode_all ($glue, $arr[$i]);
    }
    return implode($glue, $arr);
}

global $wpdb;
$titlul=get_the_title();
$titles = $GLOBALS['wpdb']->get_results("SELECT DISTINCT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title='$titlul' ", ARRAY_A);
$resultUrl = $GLOBALS['wpdb']->get_results("SELECT guid from $wpdb->posts where post_title='$titlul'", ARRAY_A);
$finalUrl = implode_all(", ",$resultUrl);

if ($titles) {
    wp_redirect("$finalUrl");
    exit;
}

我也在functions.php中尝试过,但没有奏效。

function implode_all($glue, $arr){            
for ($i=0; $i<count($arr); $i++) {
    if (@is_array($arr[$i])) 
        $arr[$i] = implode_all ($glue, $arr[$i]);
}            
return implode($glue, $arr);
}
function wp_exist_post_by_title( $title ) {
global $wpdb;
//$title= $_POST['post_title'];
$returnID = $wpdb->get_row( "SELECT ID FROM $wpdb->posts WHERE post_title 
like '%$title%' && post_status = 'publish' && post_type = 'post' order by 
ID limit 1", 'ARRAY_N' );
$resultReturnID = implode_all(", ",$returnID);
$linkPost = get_permalink("$resultReturnID");
if( empty( $returnID ) ) {
return false;
} else {
return true;
}
}

// usage
if( wp_exist_post_by_title( $post->name ) ) {
wp_redirect("$linkPost");
} 
else { 
$post_id = wp_insert_post($new_post);
}

标签: phpwordpress

解决方案


推荐阅读