Skip to content

Instantly share code, notes, and snippets.

@broskees
Created January 11, 2023 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save broskees/85c4ba0cdd7ea5d4865933c09e2f20cf to your computer and use it in GitHub Desktop.
Save broskees/85c4ba0cdd7ea5d4865933c09e2f20cf to your computer and use it in GitHub Desktop.
A custom ACF Location to be able to check if a post or custom post type (CPT) has a specific taxonomy term (supports categories). You can remove the namespace bit if you like.
<?php
namespace App;
class PostHasTerm extends \ACF_Location
{
public function initialize()
{
$this->name = 'post_has_term';
$this->label = __('Post Has Term');
$this->category = 'post';
$this->public = true;
$this->object_type = 'post';
}
public function match($rule, $screen, $field_group)
{
$rule_parts = explode('__', $rule['value']);
if (count($rule_parts) !== 2) {
throw new \Error("post_has_term location value formatted incorrectly. Should be: {taxonomy_slug}__{term_slug}");
}
$tax_slug = $rule_parts[0];
$term_slug = $rule_parts[1];
$post = get_post($screen['post_id']);
if (has_term($term_slug, $tax_slug, $post)) {
return true;
}
return false;
}
// phpcs:ignore
public function get_values($rule)
{
$terms = [];
array_map(
function ($tax) use (&$terms) {
$tax = get_taxonomy($tax);
foreach (get_terms($tax->name) as $this_term) {
$terms["{$tax->name}__{$this_term->slug}"] = "{$tax->label} / {$this_term->name}";
}
},
get_taxonomies()
);
return $terms;
}
}
acf_register_location_type(__NAMESPACE__ . '\\PostHasTerm');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment