根据当前失败的 404 请求插入新帖子,然后重定向



当用户到达 404 页面时,我正在尝试动态插入新帖子。

如果请求是:

https://supportsamsung.pl/forum/1197-pomoc-pytania-problemy/

然后,帖子标题应该是:

1197 波莫克皮塔尼亚问题

将类别设置为forum,并且用户应重定向到帖子。

它只需要处理 3 个类别。topicprofileforum。(波兰语,tematprofilforum)。

有人知道可以用于此的插件吗?如果没有,任何人都可以帮我解决这个问题吗?我已经尝试过,但无法弄清楚。

我们可以通过wp_insert_post()插入一个新帖子。我们可以将其与is_404()知道我们所在的当前页面是否是 404 页面相结合。

然后我们需要研究请求,以了解它是否符合我们的标准。我们可以通过$request = $_SERVER['REQUEST_URI'];获取请求。我们需要隔离页面,这应该是最后一个请求/1197-pomoc-pytania-problemy/,以及类别/forum/,这是最后一个请求之前的页面。

我们可以通过wp_safe_redirect()将用户重定向到帖子,并在发布时捕获帖子 ID。

经过测试并正常工作。

function endsWith( $needle, $haystack ) { //... @credit https://stackoverflow.com/a/834355/3645650
$length = strlen( $needle );
if( ! $length ) {
return true;
};
return substr( $haystack, -$length ) === $needle;
};
add_action( 'wp', 'insert_new_post_on_404_request' );
if ( ! function_exists( 'insert_new_post_on_404_request' ) ) {
function insert_new_post_on_404_request() {
if ( is_404() ) {
$request = $_SERVER['REQUEST_URI'];
if ( strpos( $request, '?' ) !== false ) {
$cleaner = substr( $request, 0, strpos( $request, '?' ) );
$request = $cleaner;
};
if ( endsWith( '/', $request ) ) {
$worker = explode( '/', substr( $request, 1, -1 ) );
} else {
$worker = explode( '/', substr( $request, 1 ) );
};
$current_category = $worker[count( $worker )-2];
$current_title = urldecode( str_replace( '-', ' ', array_pop( $worker ) ) );  

if ( ( strpos( $request, '/topic/' ) !== false )
|| ( strpos( $request, '/profile/' ) !== false )
|| ( strpos( $request, '/forum/' ) !== false ) ) {
if ( ! get_page_by_title( $current_title ) ) {
$cat_id = get_category_by_slug( $current_category )->term_id;
$postarr = array(
'post_title' => $current_title,
'post_status' => 'publish',
'post_type' => 'post',
'post_category' => array(
$cat_id,
),
);

$post_id = wp_insert_post( $postarr );
wp_safe_redirect( get_post_permalink( $post_id ) );
exit;

};
} else {
return;
}; 
};
};
};

需要考虑的一些事项:

  • 类别术语(主题、论坛和个人资料)需要在首次初始化函数之前存在。
  • 该函数只会在404.php页面上插入来自失败请求的帖子,如果这 3 个类别中的 a 中的一个存在于 url 中。
  • 如果对子页面发出请求,则可能会创建一个不附加到任何类别的帖子。 该函数无法理解它应该是一个子页面,所以我看不到任何处理这些类型请求的方法。

此外,翻译应该自己处理。 要么通过插件,要么通过其他方式。您还可以重写每个类别名称和 slug。这是基于您的主题初始开发;我们在这里能做的不多。

最新更新