Gists

1 day ago
<?php
add_action( 'facetwp_scripts', function() {
  ?>
    <script>
      document.addEventListener('facetwp-loaded', function() {
          if ( FWP.loaded ) {
              jQuery('.wp-audio-shortcode').mediaelementplayer();
          }
      });
    </script>
  <?php
}, 100 );
3 days ago
<?php
// When there are no results, Bricks does not output the facetwp-template class, leading to empty facets

// Edit the page and open the query settings for the element where Use FacetWP is enabled. 
// Scroll to the bottom of the query settings and add a text (not template) to display for No Results
// Then add the following snippet to your (child) theme's function.php
// Replace the id with the id of your Bricks element

add_filter( 'bricks/query/no_results_content', function( $content, $settings, $element_id ) {

	if ( true == ( $settings["usingFacetWP"] ?? false ) ) {
		$content = '<div id="brxe-olglkr" class="brxe-div facetwp-template">' . $content . '</div>';
	}
	return $content;

}, 10, 3 );
6 days ago
<?php
// Order by a custom field, but prevent posts from disappearing when that field does not exist for those posts.
// It first sorts by the reviews_rating field, then by post title.
// Posts without reviews_rating are sorted by title and added after the ones with the reviews_rating. 

// Important:
// - NOT EXISTS needs to be before EXISTS
// - In 'orderby' it needs to use 'meta_value_num' or 'meta_value' instead of a named meta_query segment.
// - Use 'meta_value' if the custon field is not numerical
// - The order needs to be DESC for the posts without the rating to appear after the ones with it
// See: https://wordpress.stackexchange.com/a/329687 

// Related: 
// https://gist.facetwp.com/gist/gist-bcd7971b433440a5a73b99c73b530a0f/
// https://facetwp.com/how-to-filter-or-sort-a-wp_query-by-one-or-more-custom-fields/#order-a-query-by-a-custom-field
// https://facetwp.com/how-to-filter-or-sort-a-wp_query-by-one-or-more-custom-fields/#order-a-query-by-multiple-custom-fields-that-can-be-empty-for-some-posts
// https://facetwp.com/help-center/developers/hooks/output-hooks/facetwp_facet_sort_options/#add-an-option-to-sort-by-a-custom-field-and-include-posts-without-that-field

add_filter('facetwp_facet_sort_options', function ($options, $params) {

  $options['rating'] = [

    'label' => 'Rating',
    'query_args' => [
      'meta_query' => [
        'relation' => 'OR',
        [
          'key' => 'reviews_rating',
          'compare' => 'NOT EXISTS'
        ],
        [
          'key' => 'reviews_rating',
          'compare' => 'EXISTS'
        ]
      ],
      'orderby' => [
        'meta_value_num' => 'DESC', // Order by rating first. Needs to be 'DESC'. Note: use 'meta_value' if the custom field is not numerical
        'title' => 'ASC' // Order by title second
      ],
      'meta_key' => 'reviews_rating'
    ]
  ];

  return $options;

}, 10, 2 );
7 days ago
<?php
/**
 ** Facet automatically indexes latitude and longitude from an ACF map field
 ** This will index other data saved in other sub fields
 ** Note that these fields are optional and may not exist
 ** See ACF docs for more - https://www.advancedcustomfields.com/resources/google-map/#template-usage
 **/

add_filter( 'facetwp_index_row', function( $params, $class ) {
	if ( 'my_facet' == $params['facet_name'] ) { // change my_facet to name of your facet
		$post_id = $params['post_id'];
		$acf = str_replace( 'acf/', '', $params['facet_source'] );
		$location = get_field( $acf, $post_id );
		$value = $location['city'] ?? ''; 
		if ( '' != $value ) {
			$params['facet_value'] = $value;
			$params['facet_display_value'] = $value;
		} else {
			$params['facet_value'] = ''; // don't index
		}
	}
	return $params;
}, 10, 2 );
1 week ago
<?php
// Adds wrappers with class "column-wrapper" surrounding top-level 'facetwp-checkbox' elements and their following sibling 'facetwp-depth' elements, for column styling
// Replace 'myfacetname' with the name of your facet

add_action( 'facetwp_scripts', function() {
  ?>
  <script>
    document.addEventListener('facetwp-loaded', function() {

      // Get all top-level facetwp-checkbox elements
      var checkboxes = document.querySelectorAll('.facetwp-facet-myfacetname > .facetwp-checkbox');

      // Loop through each checkbox
      checkboxes.forEach(function(checkbox) {
          
        // Create a new div element for the wrapper
        var wrapper = document.createElement('div');
        wrapper.classList.add('column-wrapper');

        // Find the next sibling div with class facetwp-depth
        var depth = checkbox.nextElementSibling;

        // Append the wrapper before the current checkbox
        checkbox.parentNode.insertBefore(wrapper, checkbox);

        // Append the checkbox element to the wrapper
        wrapper.appendChild(checkbox);

        // Check if the depth element exists and has the class facetwp-depth
        if (depth && depth.classList.contains('facetwp-depth')) {

          // Append the depth element to the wrapper
          wrapper.appendChild(depth);
        }
      });
    });
  </script>
  <?php
}, 100 );
1 week ago
<?php
/** Trigger rocket-DOMContentLoaded or DOMContentLoaded after using facets
 ** Change 'rocket-DOMContentLoaded' to 'DOMContentLoaded' if you are not using WP Rocket lazy load
 **/

add_action('facetwp_scripts', function () {
  ?>
  <script>
    document.addEventListener('facetwp-loaded', function() {
      if (FWP.loaded) {
        window.document.dispatchEvent(new Event("rocket-DOMContentLoaded", {
          bubbles: true,
          cancelable: true
        }));
      }
    });
  </script>
  <?php
}, 100);
2 weeks ago
<?php

// Function to do the term count or post count calculations:
function get_post_count_for_term_and_post_type( $term_id, $taxonomy, $post_type ) {

  $taxquery = array();

  if ($term_id && $taxonomy) {
    $taxquery = array(
      array(
        'taxonomy' => $taxonomy,
        'field' => 'id',
        'terms' => $term_id,
      )
    );
  }

  // Build the args
  $args = array(
    'post_type' => $post_type,
    'posts_per_page' => -1,
    'tax_query' => $taxquery
  );

  // Create the query
  $query = new WP_Query( $args );
  $total = $query->found_posts;

  // Return the count
  return $total;

}

// Get the number of posts for the category with id 17. Fill in the term id, taxonomy and post type:
$termcount = get_post_count_for_term_and_post_type(17,'category','post');

// Get the total number of posts for the 'post' post type.  Fill in empty strings for the term id and taxonomy, and the post type in the last argument:
$postcount = get_post_count_for_term_and_post_type('','','post');

// Percentage of posts with term 17:
$percentage = $termcount / $postcount * 100 .'%';

echo $percentage;
2 weeks ago
<?php 
// Populates a Search facet by clicking a link with a specific class.
// Add one or more links to your page with the link text as keyword:
// <a href="#" class="searchlink">keywords here</a>
// Can be used to present search suggestions: "Try this ..."
// Replace 'my_search_facet_name' with the name of your Search facet

add_action( 'facetwp_scripts', function() {
  ?>
  <script>
    (function($) {
      $('.searchlink').click(function(e) {
        e.preventDefault();
        var searchtext = $(this).text();
        FWP.facets['my_search_facet_name'] = searchtext; 
        FWP.fetchData();
        FWP.setHash();
      });
    })(jQuery);
  </script>
  <?php
}, 100 );
3 weeks ago
<?php
// Add to your (child) theme's functions.php

add_action( 'facetwp_scripts', function() {
  ?>
    <script>
      document.addEventListener('facetwp-loaded', function() {
        if (FWP.loaded) {
            FOOBOX.init();
        }
      });
    </script>
  <?php
}, 100 );
3 weeks ago
<?php
// Makes Woo product tags sortable with drag-and-drop, like product categories and attributes
// The custom sort order can be used in facets that are using product tags as data source and have "Term order" in their "Sort by" setting.

add_filter('woocommerce_sortable_taxonomies', function($taxonomies) {
  $taxonomies[] = 'product_tag';
  return $taxonomies;
});