Skip to content

Commit

Permalink
Merge branch 'mehul0810-fix/add-support-for-taxonomies' into track_cu…
Browse files Browse the repository at this point in the history
…stom_post_types
  • Loading branch information
Dan0sz committed May 17, 2024
2 parents 7e06392 + 4a44d17 commit d0f3f8d
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions src/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
use WP_Term;
use Exception;

// Bailout, if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}

class Filters {
/**
* Constructor.
Expand All @@ -22,6 +27,7 @@ class Filters {
*/
public function __construct() {
add_filter( 'script_loader_tag', [ $this, 'add_plausible_attributes' ], 10, 2 );
add_filter( 'rest_url', [ $this, 'wpml_compatibility' ], 10, 1 );
add_filter( 'plausible_analytics_script_params', [ $this, 'maybe_add_custom_params' ] );
}

Expand Down Expand Up @@ -61,6 +67,25 @@ public function add_plausible_attributes( $tag, $handle ) {
return str_replace( ' src', " {$params} src", $tag );
}

/**
* WPML overrides the REST API URL to include the language 'subdirectory', which leads to 404s.
* This forces it back to default behavior.
*
* @param mixed $url
*
* @return string|void
* @throws Exception
*/
public function wpml_compatibility( $url ) {
$rest_endpoint = Helpers::get_rest_endpoint( false );

if ( strpos( $url, $rest_endpoint ) !== false ) {
return get_option( 'home' ) . $rest_endpoint;
}

return $url;
}

/**
* Adds custom parameters Author and Category if Custom Pageview Properties is enabled.
*
Expand Down Expand Up @@ -89,15 +114,23 @@ public function maybe_add_custom_params( $params ) {
$params .= " event-author='$author_name'";
}

$categories = get_the_category( $post->ID );
// Add support for post category and tags along with custom taxonomies.
$taxonomies = get_object_taxonomies( $post->post_type );

if ( ! is_array( $categories ) ) {
return $params; // @codeCoverageIgnore
}
// Loop through existing taxonomies.
foreach ( $taxonomies as $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy );

// Skip the iteration, if `$terms` is not array.
if ( ! is_array( $terms ) ) {
continue; // @codeCoverageIgnore;
}

foreach ( $categories as $category ) {
if ( $category instanceof WP_Term ) {
$params .= " event-category='$category->name'";
// Loop through the terms.
foreach ( $terms as $term ) {
if ( $term instanceof WP_Term ) {
$params .= " event-{$taxonomy}='{$term->name}'";
}
}
}

Expand Down

0 comments on commit d0f3f8d

Please sign in to comment.