我想wp();
在文件中的行之后运行一个函数,在这里使用wp-blog-header.php
什么合适hook
?
<?php
/**
* Loads the WordPress environment and template.
*
* @package WordPress
*/
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
/********************************************
I WANT TO RUN THE FUNCTION AT THIS POINT
********************************************/
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' );
}
为什么我需要钩子
我们正在迁移到一个新网站,我们必须关心旧的 URL,所以我做了什么:
- 在我们的配置文件中添加了以下
rewrite
规则:NGINX
rewrite \D+(\/\d+\/\D+)$ /index.php?redirect=$1 break;
此规则将向 URL(旧 URL)添加一个额外参数redirect
,其中包含我将用于获取新最终 URL 的值。
- 然后,我将运行以下代码从传入 URL 中获取此值,并通过查询将每个值映射到最终 URL 的 2 列表来获取
redirect_from
最终 URLredirect_to
:
/**
* 1. Check if the URL has a parameter [redirect]
* 2. If NO, proceed to the next step
* 3. If YES, then get that parameter value and look into [redirects] table
* 4. If you found a row that has that value, then get the [redirect_to] value
* 5. Redirect to that URL [redirect_to]
*/
if (isset($_GET['redirect'])) {
// Get the parameter value from the URL
$redirect_from = $_GET['redirect'];
// Add the table prefix to the table name
$table_name = $wpdb->prefix . 'redirects';
// The SQL query
$query = "
SELECT redirect_to
FROM $table_name
WHERE redirect_from = '$redirect_from';
";
// Run the SQL query and get the results
$result = $wpdb->get_results($query, OBJECT);
// If there was a result then do the redirection and exit
if (wp_redirect($result[0]->redirect_to)) {exit;}
}
注意: 无法从旧 URL 中获取新 URL,以下是旧 URL 和新 URL 的示例:
重定向自:
http://www.example.com/category/sub-category/post-id/slug
至:
https://www.example.com/category/sub-category/yyyy/mm/dd/slug