Skip to content

Instantly share code, notes, and snippets.

@neverything
Last active August 13, 2024 14:14
Show Gist options
  • Save neverything/037b1b159371aad8adf3eb8356cd83d8 to your computer and use it in GitHub Desktop.
Save neverything/037b1b159371aad8adf3eb8356cd83d8 to your computer and use it in GitHub Desktop.
Conditionally Redirect in WordPress with full knowledge of the queried content: https://silvanhagen.com/writing/conditionally-redirect-in-wordpress/
<?php
/**
* Redirect job ads to their parent page if they are not published.
*
* @link https://developer.wordpress.org/reference/hooks/template_redirect/
* @link https://developer.wordpress.org/reference/functions/is_404/
* @link https://developer.wordpress.org/reference/functions/get_queried_object_id/
* @link https://developer.wordpress.org/reference/functions/get_post_meta/
* @link https://developer.wordpress.org/reference/functions/get_post_status/
* @link https://developer.wordpress.org/reference/functions/wp_get_post_parent_id/
* @link https://developer.wordpress.org/reference/functions/get_permalink/
* @link https://developer.wordpress.org/reference/functions/wp_redirect/
*/
add_action('template_redirect', function() {
if ( is_404() ) {
global $wp_query;
// Get the current page ID
$page_id = $wp_query->get_queried_object_id();
// Check if the current page has the meta field `is_job_ad`
$is_job_ad = get_post_meta( $page_id, 'is_job_ad', true );
// If it's a job ad and the post status is not 'publish'
if ( $is_job_ad && get_post_status($page_id) !== 'publish' ) {
// Get the parent page ID
$parent_id = wp_get_post_parent_id( $page_id );
// If there is a parent page, get its URL
if ( $parent_id ) {
$parent_url = get_permalink( $parent_id );
// 302 Redirect to the parent page URL
wp_redirect( $parent_url );
exit;
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment