So I had previously tested a specific redirect where I knew the page exists.
function nepal_template_redirect() {
if ( is_category( 'nepal' ) ) {
$url = site_url( '/nepal' );
wp_safe_redirect( $url, 301 );
exit();
} } add_action( 'template_redirect', 'nepal_template_redirect' );
However what I really want to do is include a generic function that redirects any category where a page name exists of the same name. So I thought along these lines.
function pagefromcat_template_redirect()
{
$category_id = get_cat_ID( 'Category Name' );
if (page_exists($category_id))
{
$url = site_url( '/' . $category_id);
wp_safe_redirect( $url, 301 );
}
}
add_action( 'template_redirect', 'pagefromcat_template_redirect' );
However there does not seem to be a codex item for anything like page_exists()
So how would I write a function to do this? Or is there an existing one that I have missed. Thanks
So I had previously tested a specific redirect where I knew the page exists.
function nepal_template_redirect() {
if ( is_category( 'nepal' ) ) {
$url = site_url( '/nepal' );
wp_safe_redirect( $url, 301 );
exit();
} } add_action( 'template_redirect', 'nepal_template_redirect' );
However what I really want to do is include a generic function that redirects any category where a page name exists of the same name. So I thought along these lines.
function pagefromcat_template_redirect()
{
$category_id = get_cat_ID( 'Category Name' );
if (page_exists($category_id))
{
$url = site_url( '/' . $category_id);
wp_safe_redirect( $url, 301 );
}
}
add_action( 'template_redirect', 'pagefromcat_template_redirect' );
However there does not seem to be a codex item for anything like page_exists()
So how would I write a function to do this? Or is there an existing one that I have missed. Thanks
Share Improve this question asked Sep 29, 2018 at 8:53 Andrew SeabrookAndrew Seabrook 1012 bronze badges 02 Answers
Reset to default 1get_page_by_path
does something similar:
function pagefromcat_template_redirect()
{
if ( ! is_category() ) {
return;
}
$category = get_queried_object();
$page = get_page_by_path( $category->slug );
if ( $page instanceof WP_Post )
{
$url = get_permalink( $page );
wp_safe_redirect( $url, 301 );
}
}
add_action( 'template_redirect', 'pagefromcat_template_redirect' );
Seems like I have it now. Largely due to @Michael - it requires of course that a category is exactly the same as a Page Title, but that is exactly what I want.
function pagefromcat_template_redirect() { if ( ! is_category() ) { return; }
$category = get_queried_object();
// $page = get_page_by_path( $category->slug ); -- doesnt work
// $page = get_page_by_path( 'destinations/' . $category->slug); works but with deeper nested locations this will cause a problem, and we will have to have multiple prefixed locations
// atcivities immediately for instance.
$page = get_page_by_title($category->name);
if ( $page instanceof WP_Post )
{
$url = get_permalink( $page );
wp_safe_redirect( $url, 301 );
}
}