Localization inside shortcode not working

I use a shortcode that retrieves the url of woocommerce products and builds a link:

function woo_url_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );
    $html = '';
    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ) {
        $_product = wc_get_product( $atts['id'] );
        $html = $_product->get_permalink();
    }
    $text = 'Some text';
        return '<p class="woo-booking"><a href="'.$html.'">'.$text.'</a></p>';
}

Works fine. But now I need the text translated like this:

esc_html_e( 'Some text', 'generatepress-child' );

So, the code would be:

function woo_url_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );
    $html = '';
    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ) {
        $_product = wc_get_product( $atts['id'] );
        $html = $_product->get_permalink();
    }
        return '<p class="woo-booking"><a href="'.$html.'">'.esc_html_e( 'Some text', 'generatepress-child' ).'</a></p>';
}

Language files are there and working. But not with this shortcode. The string is translated but appears at the top of the page and is repeated several times. What exactly am I missing, and how can I fix this?

Thank you!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

esc_html_e() displays (echo) the output, hence it appears at the wrong place. So you should instead use esc_html__() which returns the translated string.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x