Last active
March 21, 2024 10:02
-
-
Save JoKolov/171548c2c3f2474995ee8c61d9f8d455 to your computer and use it in GitHub Desktop.
WordPress shortcode Contact Form 7 Locale : [contact-form-7-locale default="{id}" en="{id}"]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ( ! function_exists( "a3w_locale_contact_form_7_shortcode" ) ) : | |
add_shortcode( "contact-form-7-locale", "a3w_locale_contact_form_7_shortcode" ); | |
/* | |
* Shortcode [contact-form-7-locale default="0" fr="0" es="0"] | |
* Display CF7 form depending on locale | |
* | |
* Usage example: | |
* [contact-form-7-locale default="{cf7_form_id}" en="{cf7_form_id_en}" html_id="{cf7_form_id_optional}" html_class="{cf7_form_class_optional}"] | |
* | |
* Explaination | |
* default="{cf7_form_id}" => Register default CF7 form for default language or unknow language | |
* en="{cf7_form_id_en}" => Register CF7 form for specfic language (can use short locale [en] or long [en_US]) | |
* html_id="{cf7_form_id_optional}" & html_class="{cf7_form_class_optional}" => same usage as default CF7 shortcode | |
* @see https://contactform7.com/faq/can-i-add-id-and-class-attributes-to-a-form-element/ | |
* | |
* @param array $atts shortcode attributes | |
* @return string Form HTML | |
*/ | |
function a3w_locale_contact_form_7_shortcode( $atts ) { | |
$atts = array_merge( [ | |
'default' => '', // mandatory: default cf7 id for default language | |
'html_id' => '', // same use as cf7 shortcode | |
'html_class' => '', // same use as cf7 shortcode | |
], $atts ); | |
if ( empty( $atts[ 'default' ] ) ) return ""; | |
$form_id = $atts['default']; | |
$current_locale = get_locale(); | |
$current_locale_array = explode( '_', $current_locale ); | |
$current_locale_short = $current_locale_array[0]; | |
if ( array_key_exists( $current_locale, $atts ) ) { | |
$form_id = trim( $atts[$current_locale] ); | |
} elseif ( array_key_exists( $current_locale_short, $atts ) ) { | |
$form_id = trim( $atts[$current_locale_short] ); | |
} | |
$cf7_shortcode = sprintf( '[contact-form-7 id="%s" %s %s]', | |
$form_id, | |
empty( $atts['html_id'] ) ? "" : 'html_id="' . esc_attr( $atts['html_id'] ) . '"', | |
empty( $atts['html_class'] ) ? "" : 'html_class="' . esc_attr( $atts['html_class'] ) . '"' | |
); | |
ob_start(); | |
echo do_shortcode( $cf7_shortcode ); | |
return ob_get_clean(); | |
} | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
you can use it to display specific contact form 7 depending on current locale in WordPress website.
Enjoy :)