Translate Listing Builder items with WPML

<?php
// Note: in FacetWP 4.3.2 the facetwp_i18n hook was added to the Button item, making it easier to translate the Button text.
// See: https://facetwp.com/help-center/listing-templates/listing-builder/#translate-the-button-item-text
// The solutions below can still be used for older FacetWP versions and other items.


// To tranlate a Button item's Button text:

add_filter( 'facetwp_builder_item_value', function( $value, $item ) {

  if ( 'el-2epdx' == $item['settings']['name']  ) { // Replace 'el-2epdx' with the name of your listing builder item

    $lang = ( ! empty( FWP()->facet->http_params['lang'] ) ) ? FWP()->facet->http_params['lang'] : apply_filters( 'wpml_current_language', null );
    switch ( $lang ) {
      case 'en' :
        $value = 'My english button text';
        break;
      default :
        $value = 'Default button text';
    }
  }

  return $value;
}, 10, 2 );


// If the Button has a link set, use this instead:
add_filter( 'facetwp_builder_item_value', function( $value, $item ) {

  if ( 'el-pgnldu' == $item['settings']['name']  ) { // Replace 'el-2epdx' with the name of your listing builder item

    $lang = ( ! empty( FWP()->facet->http_params['lang'] ) ) ? FWP()->facet->http_params['lang'] : apply_filters( 'wpml_current_language', null );

    switch ( $lang ) {
      case 'en' :
        $text = 'My english button text';
        break;
      default :
        $text = 'Default button text';
    }

    $dom = new DOMDocument();
    $dom->loadHTML($value);

    $link = $dom->getElementsByTagName('a')->item(0);
    $link->nodeValue = $text;

    $value= $dom->saveHTML();
  }

  return $value;
}, 10, 2 );