How can you wrap add_filter with a if is_home() statement?

I have the follow code:

if ( !function_exists( 'df_excerpt_more' ) ) {

   function df_excerpt_more( $more ) {
       return ' hellip; a class="more-link" href="' . esc_url( get_permalink( get_the_ID() ) ) . '"' . esc_attr__( 'Read More', 'applique' ) . 'i class="ion-ios-arrow-thin-right"/i/a';
   }

   add_filter( 'excerpt_more', 'df_excerpt_more' );

}

I'd like to add a second line of "add_filter" and execute it only if page is home. So I'm trying this:

if ( !function_exists( 'df_excerpt_more' ) ) {

   function df_excerpt_more( $more ) {
       return ' hellip; a class="more-link" href="' . esc_url( get_permalink( get_the_ID() ) ) . '"' . esc_attr__( 'Read More', 'applique' ) . 'i class="ion-ios-arrow-thin-right"/i/a';
   }

   add_filter( 'excerpt_more', 'df_excerpt_more' );

   //second filter if is home like this:
   if ( is_home() ) :
     add_filter('get_the_excerpt', 'df_excerpt_more');
   endif;

}

For some reason this isn't working. Seems like something very simple. What am I missing?

Topic filters page-specific-settings Wordpress

Category Web


The is_home() function isn't available until the parse_query action. So you'd probably want to rewrite your code like so:

if ( ! function_exists( 'df_excerpt_more' ) ) {

    function df_excerpt_more( $more ) {
        return ' &hellip; <a class="more-link" href="' . esc_url( get_permalink( get_the_ID() ) ) . '">' . esc_attr__( 'Read More', 'applique' ) . '<i class="ion-ios-arrow-thin-right"></i></a>';
    }

}

add_action( 'parse_query', 'df_add_excerpt_filters' );

function df_add_excerpt_filters() {

    add_filter( 'excerpt_more', 'df_excerpt_more' );

    if ( is_home() ) :
        add_filter( 'get_the_excerpt', 'df_excerpt_more' );
    endif;

}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.