Question

I have a function that adds a class based on various statements, certain pages, cpt's you're on etc.

I put this function in various sections within the page for styling purposes using <?php is_service_class() ?>

I'm not sure if this is the correct way of doing this but it kind of works however, i'm just wondering why it only works once? I'm trying to learn about functions and the rights and wrongs.

if ( ! function_exists( 'is_service_class' ) ) {

function is_service_class () {


    if ( ! function_exists( 'is_personal' ) ) { 

        function is_personal() {
            return ( is_post_type_archive('pk-personal') || is_singular( 'pk-personal' ) || is_page( array( 6814, 'personal-family', 'Personal & Family Services' ) ) ) ? true : false ;

        }

        if ( is_personal() ) {
            echo 'personal-service'; 
        } 

    }

    if ( ! function_exists( 'is_business' ) ) {

        function is_business() {
            return ( is_post_type_archive('pk-business')  || is_singular( 'pk-business' ) || is_page( array( 6821, 'business-services', 'Business Services' ) ) ) ? true : false ;

        }

        if ( is_business() ) {
            echo 'business-service'; 
        } 

    }


}
}
Was it helpful?

Solution

Function "works" once because before first call of is_service_class(), function is_personal not exists and whole this block is executed

if ( ! function_exists( 'is_personal' ) ) { 
    // declaration and use of function
}

In next call of is_service_class() is_personal is declared and the entire block is skipped. Inside the condition if ( !function_exists( 'is_personal' ) ) leave only the declaration:

if ( !function_exists( 'is_personal' ) ) { 

    function is_personal() {
        return ( is_post_type_archive('pk-personal') || is_singular( 'pk-personal' ) || is_page( array( 6814, 'personal-family', 'Personal & Family Services' ) ) ) ? true : false ;
    }
}
if ( is_personal() ) {
    echo 'personal-service'; 
} 

Similary is with is_business().


I would suggest this form:

if ( !function_exists( 'is_service_class' ) ) {

    function is_service_class () {

        if ( is_personal() ) {
            echo 'personal-service'; 
        } 
        if ( is_business() ) {
            echo 'business-service'; 
        } 
    }
}

if ( !function_exists( 'is_personal' ) ) { 

    function is_personal() {
        return ( is_post_type_archive('pk-personal') || is_singular( 'pk-personal' ) 
            || is_page( array( 6814, 'personal-family', 'Personal & Family Services' ) ) ) ? true : false ;
    }
}
if ( !function_exists( 'is_business' ) ) {

    function is_business() {
        return ( is_post_type_archive('pk-business')  || is_singular( 'pk-business' ) 
            || is_page( array( 6821, 'business-services', 'Business Services' ) ) ) ? true : false ;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top