How Can We Help?

WPML Post Language rules

You are here:
< All Topics

In order to use WPML post language rules to send a post in specific language to a specific channel/group on Telegram, you can make use of the custom code as below:

After you add the code, you can the Post Language rule in instance settings.

We recommend My Custom Functions plugin to add the code safely. Otherwise, you can add the code to functions.php of your child theme.

/* PHP >= 5.6 */
/**
 * Register the Post Language rule type to display in
 * instance rules dropdown
 */
add_filter(
	'wptelegram_pro_p2tg_rule_types',
	function ( $rule_types ) {
		$rule_types[] = array(
			'label'   => __( 'WPML', 'text-domain' ),
			'options' => array(
				array(
					// value is the unique ID for the rule
					'value' => 'post_lang',
					'label' => __( 'Post Language', 'text-domain' ),
				),
			),
		);
		return $rule_types;
	}
);

/**
 * Return the active languages to select in instance rules
 */
add_filter(
	'wptelegram_pro_p2tg_rule_values',
	function ( $options, $param ) {
		// if it's our registered rule
		if ( 'post_lang' === $param ) {
			$languages = apply_filters( 'wpml_active_languages', array() );
			$options   = array();
			foreach ( $languages as $language ) {
				$label     = sprintf(
					'%1$s (%2$s)',
					$language['native_name'],
					$language['translated_name']
				);
				// two letter language code e.g. "en"
				$value     = $language['language_code'];
				$options[] = compact( 'value', 'label' );
			}
		}
		return $options;
	},
	10,
	2
);

/**
 * Return the post language when post rules are checked
 * to decide whether the rule applies to a post.
 */
add_filter(
	'wptelegram_pro_p2tg_rules_post_data_for_param',
	function ( $data, $param, $options, $post ) {
		// if it's our registered rule
		if ( 'post_lang' === $param ) {
			$post_lang = apply_filters( 'wpml_post_language_details', null, $post->ID );
			if ( ! empty( $post_lang['language_code'] ) ) {
				$data = array( $post_lang['language_code'] );
			}
		}
		return $data;
	},
	10,
	5
);

/**
 * Get WPML translated post URL
 * 
 * You can then use {cf:wmpl_url:ar}, {cf:wpml_url:fr}
 */
add_filter(
	'wptelegram_pro_p2tg_post_data_field_value',
	function ( $value, $field, $post ) {
		if ( preg_match( '/^cf:wpml_url:([a-z]+)$/', $field, $match ) ) {
			$permalink = urldecode_deep( get_permalink( $post->ID ) );
			$permalink = apply_filters( 'wpml_permalink', $permalink, $match[1], true );
			return $permalink;
		}
		return $value;
	},
	10,
	3
);

Please note that {full_url} does not work for translated posts. So, you will need to use something like {cf:wmpl_url:ar}, {cf:wpml_url:fr} etc.

Table of Contents

Ready to dive in? Buy NOW