I’m trying to do a string replacement using gettext filter (source):

function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {
    if( stripos( $untranslated_text, 'comment' !== FALSE ) ) {
        $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;
    }
    return $translated_text;
}
is_admin() && add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );

I want it to work only on a specific Post Type (in admin). So I tried get_current_screen() within the function:

function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {
    $screen = get_current_screen();
    if( $screen->post_type == 'mycpt' ) {
        if( stripos( $untranslated_text, 'comment' !== FALSE ) ) {
            $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;
        }
        return $translated_text;
    }
}
is_admin() && add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );

But I’m getting error:

Fatal error: Call to undefined function get_current_screen()

With several testing I understood, gettext is not the correct filter to trigger the get_current_screen() function.

Then how could I do that, specific to my custom post type only?

2 s
2

According with the codex, get_current_screen() has to be used later than admin_init hook. After a few tests, it seems that the safiest way is to use current_screen action hook instead of get_current_screen():

add_action('current_screen', 'current_screen_callback');
function current_screen_callback($screen) {
    if( is_object($screen) && $screen->post_type == 'mycpt' ) {
        add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );
    }
}

function theme_change_comments_label( $translated_text, $untranslated_text, $domain ) {

    if( stripos( $untranslated_text, 'comment' ) !== FALSE ) {
        $translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;
    }

    return $translated_text;

}

You can reuse the filter if you want, for example in the frontend for “mycpt” archives:

add_action('init', function() {
    if( is_post_type_archive( 'mycpt' ) ) {
        add_filter( 'gettext', 'theme_change_comments_label', 99, 3 );
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *