wordpress - 根据当前失败的 404 请求插入新帖子,并重定向
问题描述
我试图在用户到达 404 页面时动态插入新帖子。
如果请求是:
https://supportsamsung.pl/forum/1197-pomoc-pytania-problemy/
然后,帖子标题应该是:
第1197章
将类别设置为forum
,用户应该被重定向到帖子。
它只需要处理3个类别。topic
,profile
和forum
. (在波兰语中,,,temat
)profil
forum
。
有人知道可以用于此的插件吗?如果没有,有人可以帮我解决这个问题吗?我已经尝试过,但无法弄清楚。
解决方案
我们可以通过 插入新帖子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
如果 URL 中存在这 3 个类别中的 1个,该函数只会在页面上插入来自失败请求的帖子。- 如果请求子页面,它可能会创建一个不附加到任何类别的帖子。该函数无法理解它应该是一个子页面,所以我看不到任何处理这些类型请求的方法。
此外,翻译应自行处理。通过插件或其他方式。您还可以重写每个类别名称和 slug。这是基于您的主题初步开发;我们在这里无能为力。
推荐阅读
- ionic-framework - 限制 IONIC 侧边菜单自动填充大屏幕
- chart.js - 使用 Chart.js 在多线线性图上的单点
- ios - Riot-iOS 错误:运行 bundle exec pod install 时
- weblogic - Weblogic:启动配置向导时 config.cmd 不起作用
- python-3.x - 无法调用 FBO.gov 的 Web API 提供的任何方法
- database - 以最少的查询在数据库前面设计一个缓存层
- syntax - @ 选项运算符如何在 AEM HTL 模板中工作
- mysql - 从mysql中的对象数组中删除json对象
- c++ - 返回非常量引用会导致绑定引用错误
- ruby-on-rails - ActiveStorage 可以创建一个 blob 用于直接上传并在上传完成之前将其附加到模型吗?