• 916VT

    (@vincent916)


    Hi there,

    As titled, I’m looking for acting on my parent categories only, without touching about their childs.

    At the end, I would like to redirect url/category/parent/ (which is a category) to url/parent/ (which is a page).

    So I’m thinking about using wp_redirect() but I need to apply it to the right moment.

    I found that topic that is also about parent category but the code influence child categories.

    <?php
        $category = get_the_category();
        if ($category[0]->category_parent != '') {echo 'hello world!' ;} ?>

    Does anyone know something to target only my category parents ?

    Thanks a lot for helping,
    Vinc

Viewing 3 replies - 1 through 3 (of 3 total)
  • Daniel Homer

    (@danielhomer)

    Try this code inside your functions.php

    add_action( 'template_redirect', 'redirect_parent_category' );
    
    function redirect_parent_category() {
    	if ( ! is_category() ) {
    		return;
    	}
    
    	$cat = get_query_var( 'cat' );
    	$term = get_term( $cat, 'category' );
    
    	if ( ! $term->parent ) {
    		wp_safe_redirect( '/' . $term->slug, 301 );
    		exit();
    	}
    }

    I haven’t tested it, but it should redirect any category archives without a parent to /<slug>.

    Thread Starter 916VT

    (@vincent916)

    Hello Daniel,

    It looks to work just perfectly ! Awesome !

    I was reading Google result pages for hours… :’)

    Thanks a lot for your help, really appreciated
    Vinc

    Thread Starter 916VT

    (@vincent916)

    Hi Daniel,

    Maybe you may help me again with that.

    I installed SEO WP by Yoast and use the function to remove /category/ on my url. Now, the function you provided above doesn’t work.

    Do you think it’s possible to fix that somehow ?

    Thanks again

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Looking for acting on parent categories only’ is closed to new replies.