Gists

1 week ago
<?php
// If you are using an ACF Color Picker field as facet data source,
// you can use the color value (hex or rgb(a)) to give a (background) color to the facet choice.
// It is important to use the facet_display_value for the color, and not the facet_value, 
// because the facet_value will be hashed into a random string of numbers due to unsafe URL characters.
// Note: for fSelect facets, you need to use esc_html() around the label output in L11, otherwise the HTML will be stripped out.
// More info: https://facetwp.com/help-center/using-facetwp-with/advanced-custom-fields/#using-a-color-picker-field

add_filter( 'facetwp_facet_display_value', function( $label, $params ) {
  if ( 'my_color_facet' == $params['facet']['name'] ) { // Replace 'my_color_facet' with the name of your color picker based facet.
    $val = $params['row']['facet_display_value']; // Use the display value here to get the unhashed hex or rgb(a) color value.
    $label = '<span style="background-color:' . $val . ';">' . $label . '</span>'; // Add a span to the facet choice with the color as CSS background color.
  }
  return $label;
}, 20, 2 );
1 week ago
<?php
// Index birthday dates in a custom date field (stored as YYYY-MM-DD) as age.
// This facet can then filter by age range, for example in a Range List facet type:
// https://facetwp.com/help-center/facets/facet-types/range-list/
// E.g.
// under 50
// 50-60
// 60-70
// 70-80
// 80-90
// 90+

add_filter( 'facetwp_index_row', function( $params, $class ) {
  if ( 'my_facet_name' == $params['facet_name'] ) { // change "my_facet_name" to the name of your date-based facet
    $raw_value = $params['facet_value']; // date needs to be in YYYY-MM-DD format

    $birthdate = new DateTime($raw_value);
    $now = new DateTime('now');
    $interval = $birthdate->diff($now);
    $age = $interval->y; // age in years
    
    $params['facet_value'] = $age;
    $params['facet_display_value'] = $age;
  }
  return $params;
}, 10, 2 );
1 week ago
<?php
// FacetWP does NOT officially support TranslatePress. It supports WPML and Polylang, with the Multilingual add-on:
// https://facetwp.com/help-center/using-facetwp-with/multilingual/

// Some users do use TranslatePress successfully with FacetWP.
// However, we get reports of inconsistent translations of facet choices before and after facet filtering.
// These issues are reportedly solved by adding this refresh snippet to the (child) theme's functions.php:

add_action('facetwp_scripts', function () {
  ?>
  <script>
    document.addEventListener('facetwp-refresh', function() {
      if ( !FWP.loaded ) {
        FWP.loaded = true;
        FWP.refresh();
      }
    });
  </script>
  <?php
}, 100);
3 weeks ago
<?php
// Add an element that shows the post number and total, e.g. 1 of 28
// to the top of each Listing Builder listing post item.
// This code works for "Page numbers" and "Load More" Pager facets. 
// Make sure your page does not include both Pager facet types.

// Note: if you are using the Listing Builder in Dev mode, it would be better to do this directly in the template code like this:
// https://gist.facetwp.com/gist/post-counter-in-query-with-paged-pages/

add_action( 'facetwp_scripts', function() {
  ?>

  <script>

    document.addEventListener('facetwp-loaded', function() {

      // Calculate the first post number on the page:
      let page = FWP.settings.pager.page;
      let per_page = FWP.settings.pager.per_page;
      let total = FWP.settings.pager.total_rows;
      let firstofpage = 1;

      // Check for "Load more" Pager facets
      let is_loadmore = document.querySelector('.facetwp-load-more') !== null;

      if (is_loadmore) {
        // For "Load more" Pager facets
        firstofpage = 1;
      } else {
        // For "Page numbers" Pager facets
        if (per_page < total) {
          firstofpage = (1 + ((page - 1) * per_page));
        } else {
          firstofpage = (0 < total) ? 1 : 0;
        }
      }

      // Select all post elements with class .fwpl-col
      let posts = document.querySelectorAll('.fwpl-col');

      // Loop through each post element:
      posts.forEach((post, index) => {

        // Check if the post already has the item-number element (for when using a Load more Pager facet)
        if (!post.querySelector('.item-number')) {

          // Set the actual post number, which is the number of the first plus the index that starts at 0:
          let postnumber = index + firstofpage;

          let textDiv = document.createElement('div');
          textDiv.classList.add('item-number');
          textDiv.textContent = (postnumber) + ' of ' + total;

          // Get the first child of the post element
          var firstChild = post.firstChild;

          // Prepend 'textDiv' before the first child element
          post.insertBefore(textDiv, firstChild);

        }

      });

    });

  </script>

  <?php
}, 100 );
4 weeks ago
<?php
// Adds a div with class "item-number" to each Listing Builder listing item, 
// with a counter text that counts the builder items in the post: e.g. "# of total", e.g. "1 of 20".

add_action( 'facetwp_scripts', function() {
  ?>

  <script>

    document.addEventListener('facetwp-loaded', function() {

      // Select all parent elements with class .fwpl-col
      const parentElements = document.querySelectorAll('.fwpl-col');

      // Loop through each parent element
      parentElements.forEach(parentElement => {

        // Select direct child elements with class .fwpl-item
        const childElements = Array.from(parentElement.children).filter(child => child.classList.contains('fwpl-item'));

        // Set the total number of items
        const totalItems = childElements.length;

        // Add a div with the text to each child element
        childElements.forEach((childElement, index) => {
          // Create a new div element
          const textDiv = document.createElement('div');
          textDiv.classList.add('item-number');
          textDiv.textContent = (index + 1) + ' of ' + totalItems;

          // Append the text div to the child element
          childElement.appendChild(textDiv);
        });
      });

    });

  </script>

  <?php
}, 100 );
4 weeks ago
<?php

/** indexes only child or deeper level terms **/
add_filter( 'facetwp_index_row', function( $params ) {
    if ( 'product_categories' == $params['facet_name'] ) { //change 'product_categories' to name of your facet
		if ( 1 > $params['depth'] ) { // adjust this for different term levels as needed 
			$params['facet_value'] = ''; // skip indexing
		}
	}
	return $params;
});
4 weeks ago
<?php

/** Indexes all values of an ACF 'endorsement' Checkbox field (set to output an array of 'value : label' choices),
 ** for posts of post type 'csg_brand' that have a company ID field set.
 ** See: https://facetwp.com/help-center/developers/hooks/indexing-hooks/facetwp_index_row/
 */


add_filter( 'facetwp_index_row', function( $params, $class ) {

  // The 'refine_by' facet is set up with 'Post Type' as data source. 'csg_brand' is a post type.
  if ( 'refine_by' == $params['facet_name'] && 'csg_brand' == $params['facet_value'] ) {

    $post_id = $params['post_id'];

    // Get the company ID from the current 'csg_brand' post
    $company_id = get_post_meta( $post_id, 'company', true );
    $company_id = $company_id[0];

    if ( isset( $company_id ) && $company_id > 0 ) {

      $field = get_field_object( 'endorsements', $company_id );
      $checkboxes_values = $field['value'];

      foreach ( $checkboxes_values as $checkbox_value ) {

        if ( is_array( $checkbox_value ) ) {
          $facet_value = FWP()->helper->safe_value( $checkbox_value['value'] );
          $facet_display_value = $checkbox_value['label'];

        } else {
          $facet_value = FWP()->helper->safe_value( $checkbox_value );
          $facet_display_value = $checkbox_value;
        }

        $params['facet_value'] = $facet_value;
        $params['facet_display_value'] = $facet_display_value;
        $class->insert( $params );

      }

      $params['facet_value'] = ''; // skip the original row

    } else {

      // No valid company ID found, set facet_value to empty to avoid indexing
      $params['facet_value'] = ''; // skip indexing
    }

  }

  return $params;

}, 10, 2 );
4 weeks ago
<?php

/** Filters the search block form to replace the "s" input with your Search facet. Change "_keywords" (the Search facet's name) as needed.
 ** This also replaces the default action with the page URL of your custom search results page. Change the "/site-search/" permalink as needed. 
 ** See: https://facetwp.com/redirect-a-search-box-to-a-facetwp-results-page/
 */

add_filter('render_block', function ($block_content = '', $block = []) {
    if (isset($block['blockName']) && 'core/search' === $block['blockName']) {
        $block_content = preg_replace('/action="(.*?)"/', 'action="/site-search/"', $block_content);
        $block_content = preg_replace('/name="(.*?)"/', 'name="_keywords"', $block_content);
    }
    return $block_content;
}, 11, 2);
4 weeks ago
<?php
/** Add your message in an element with the class 'facetwp-load-more-complete' where you want the
 ** no more results message to display.
 ** for ex.   <div class="facetwp-load-more-complete facetwp-hidden">That's all</div>
 ** See: https://facetwp.com/help-center/facets/facet-types/pager/#display-a-no-more-results-message-below-the-load-more-button
 **/

add_action('facetwp_scripts', function () { ?>
    <script>
        (function($) {
            $().on('facetwp-loaded', function() {
                var is_visible = (FWP.settings.pager.page < FWP.settings.pager.total_pages);
                var method = is_visible ? 'addClass' : 'removeClass';
                $('.facetwp-load-more-complete')[method]('facetwp-hidden');
            });
        })(fUtil);
    </script>
<?php }, 100);
1 month ago
<?php
// Automatically updates the text in a specific <h1> heading tag on the page with the display value of the selected choice of a specific facet.
// Assumes the facet is a single-choice type facet (e.g. Dropdown or Radio).

add_action( 'wp_head', function() {
  ?>
  <script>
    document.addEventListener('facetwp-loaded', function() { // Runs after the refresh process, on each AJAX page load, and on the initial page load.   
      let selected = FWP.facets['pubtype']; // Replace "pubtype" with the name of your facet
      if ( selected.length ) { // If any choice in this facet is selected

        // Find the <h1> tag with class "page-title"
        var h1WithTitle = document.querySelector('h1.page-title');

        // Update the text content of the <h1 class="page-title"> tag
        if ( h1WithTitle ) {
          h1WithTitle.textContent = selected;
        }  
      }
    });     
  </script>
  <?php
}, 100 );