How to run a function after wp() in the wp-blog-header.php file?
I want to run a function after the wp();
line in the file wp-blog-header.php
, what is the proper hook
to use here?
?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' );
}
Why do I need the hook
We are migrating to a new website and we have to care about the old URLs, so what I did:
- Added the following
rewrite
rule to ourNGINX
config file:
rewrite \D+(\/\d+\/\D+)$ /index.php?redirect=$1 break;
This rule will add an extra parameter redirect
to the URL (old URL) with a value that I will be using to get the new final URL.
- Then I will run the following code to get this value from the incoming URL and get the final URL by querying a 2-columns table that maps each value
redirect_from
with a final 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;}
}
Note: No way to get the new URLs from old URLs, here is an example of the old and new URLs:
Redirect from:
http://www.example.com/category/sub-category/post-id/slug
to:
https://www.example.com/category/sub-category/yyyy/mm/dd/slug
Topic wp-blog-header.php actions hooks Wordpress
Category Web