WPML/Polylang translation shortcode

/**
 * wpcodebook_translate.
 *
 * @see https://wpcodebook.com/snippets/wpml-polylang-translation-shortcode/
 */
add_shortcode( 'wpcodebook_translate', function ( $atts, $content = '' ) {

    // E.g.: `[wpcodebook_translate lang="EN,DE" lang_text="Text for EN & DE" not_lang_text="Text for other languages"]`
    if ( isset( $atts['lang_text'] ) && isset( $atts['not_lang_text'] ) && ! empty( $atts['lang'] ) ) {
        return ( ! defined( 'ICL_LANGUAGE_CODE' ) || ! in_array( strtolower( ICL_LANGUAGE_CODE ), array_map( 'trim', explode( ',', strtolower( $atts['lang'] ) ) ) ) ) ?
            $atts['not_lang_text'] : $atts['lang_text'];
    }

    // E.g.: `[wpcodebook_translate lang="EN,DE"]Text for EN & DE[/wpcodebook_translate][wpcodebook_translate not_lang="EN,DE"]Text for other languages[/wpcodebook_translate]`
    return (
        ( ! empty( $atts['lang'] )     && ( ! defined( 'ICL_LANGUAGE_CODE' ) || ! in_array( strtolower( ICL_LANGUAGE_CODE ), array_map( 'trim', explode( ',', strtolower( $atts['lang'] ) ) ) ) ) ) ||
        ( ! empty( $atts['not_lang'] ) &&     defined( 'ICL_LANGUAGE_CODE' ) &&   in_array( strtolower( ICL_LANGUAGE_CODE ), array_map( 'trim', explode( ',', strtolower( $atts['not_lang'] ) ) ) ) )
    ) ? '' : $content;

} );

Leave a Comment