将自定义分类术语存档重定向到页面



我希望将我的术语模板重定向到带有save slug的页面(以允许客户端自定义页面并为此页面使用模板模型(,这是我的代码

function redirect_archive_term() {

$categories = get_terms( array('taxonomy' => 'chapters') );
foreach($categories as $category) {

if( is_post_type_archive( $category->slug ) ) { // like chapter-1, chapter-2 ...
wp_redirect( home_url( '/'.$category->slug ), 301 );
exit();
}
}
}
add_action( 'template_redirect', 'redirect_archive_term' );

这是行不通的,因为我认为,有办法针对他们吗?

感谢您的帮助:(

应该非常直接。以下内容未经测试。

函数必须在部署标头之前激发,从而使用wp钩子。

is_tax()可以在搜索或存档页面上触发,我们需要将其过滤掉,因此! is_search() && ! is_archive()

我们从get_term()获得当前项,并通过wp_safe_redirect()重定向。

<?php
/**
* Redirect term page to the corresponding custom slug page.
* 
* @see https://stackoverflow.com/questions/71266569/redirect-custom-taxonomy-terms-archive-to-page
* 
* @since   1.0.0
* 
* @param   void
* @return  void
*/
add_action( 'wp', 'wpso_71266569' );  //hook into wp's init action hook
if ( ! function_exists( 'wpso_71266569' ) ) {

function wpso_71266569() {

//Let's make sure we're on a taxonomy "chapters" page:
//Either taxonomy-{taxonomy}.php or taxonomy-{taxonomy}-{term}.php.
if ( ! is_search() && ! is_archive() && is_tax( 'chapters' ) ) {

$term = get_term( get_queried_object_id() ); //Retrieve the current term slug.

wp_safe_redirect( home_url( trailingslashit( $term->slug ) ) ); //eg: Redirect to https://example.com/term_slug/.

};

};

};

最新更新