Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added: Search Queries option, which allows tracking of search events. #213

Merged
merged 14 commits into from
Jun 7, 2024
Merged
31 changes: 29 additions & 2 deletions src/Actions.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,38 @@ public function maybe_register_assets() {
);

// Track 404 pages (if enabled)
if ( is_array( $settings[ 'enhanced_measurements' ] ) && in_array( '404', $settings[ 'enhanced_measurements' ] ) && is_404() ) {
if ( Helpers::is_enhanced_measurement_enabled( '404' ) && is_404() ) {
$data = wp_json_encode(
[
'props' => [
'path' => 'documentation.location.pathname',
],
]
);

wp_add_inline_script(
'plausible-analytics',
"document.addEventListener('DOMContentLoaded', function () { plausible('404', { props: { path: document.location.pathname } }); });"
"document.addEventListener('DOMContentLoaded', function () { plausible( '404', $data ); });"
);
}

// Track search results. Tracks a search event with the search term and the number of results, and a pageview with the site's search URL.
if ( Helpers::is_enhanced_measurement_enabled( 'search' ) && is_search() ) {
global $wp_rewrite, $wp_query;

$search_url = str_replace( '%search%', '', get_site_url( null, $wp_rewrite->get_search_permastruct() ) );
$data = wp_json_encode(
[
'props' => [
'search_query' => get_search_query(),
'result_count' => $wp_query->found_posts,
],
]
);
$script = 'plausible("pageview", {u:"' . esc_attr( $search_url ) . '"});';
$script .= "\nplausible('Search', $data );";

wp_add_inline_script( 'plausible-analytics', "document.addEventListener('DOMContentLoaded', function() {\n$script\n});" );
}

// This action allows you to add your own custom scripts!
Expand Down
33 changes: 31 additions & 2 deletions src/Admin/Provisioning.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ class Provisioning {
'category',
];

private $custom_search_properties = [
'search_query',
'result_count',
];

/**
* Build class.
*
Expand Down Expand Up @@ -63,6 +68,7 @@ public function __construct( $client = null ) {
'404' => __( '404', 'plausible-analytics' ),
'outbound-links' => __( 'Outbound Link: Click', 'plausible-analytics' ),
'file-downloads' => __( 'File Download', 'plausible-analytics' ),
'search' => __( 'Search', 'plausible-analytics' ),
];

$this->init();
Expand Down Expand Up @@ -140,6 +146,13 @@ public function maybe_create_goals( $old_settings, $settings ) {
}

$goals[] = $this->create_request_custom_event( $this->custom_event_goals[ $measurement ] );

if ( $measurement === 'search' ) {
global $wp_rewrite;

$search_url = str_replace( '%search%', '', $wp_rewrite->get_search_permastruct() );
$goals[] = $this->create_request_custom_event( null, 'Pageview', '', $search_url );
}
}

$this->create_goals( $goals );
Expand All @@ -152,7 +165,7 @@ public function maybe_create_goals( $old_settings, $settings ) {
*
* @return GoalCreateRequestCustomEvent
*/
private function create_request_custom_event( $name, $type = 'CustomEvent', $currency = '' ) {
private function create_request_custom_event( $name, $type = 'CustomEvent', $currency = '', $path = '' ) {
$props = [
'goal' => [
'event_name' => $name,
Expand All @@ -164,6 +177,12 @@ private function create_request_custom_event( $name, $type = 'CustomEvent', $cur
$props[ 'goal' ][ 'currency' ] = $currency;
}

if ( $type === 'Pageview' ) {
unset( $props[ 'goal' ][ 'event_name' ] );

$props[ 'goal' ][ 'path' ] = $path;
}

return new Client\Model\GoalCreateRequestCustomEvent( $props );
}

Expand Down Expand Up @@ -267,7 +286,8 @@ public function maybe_create_custom_properties( $old_settings, $settings ) {
$enhanced_measurements = $settings[ 'enhanced_measurements' ];

if ( ! Helpers::is_enhanced_measurement_enabled( 'pageview-props', $enhanced_measurements ) &&
! Helpers::is_enhanced_measurement_enabled( 'revenue', $enhanced_measurements ) ) {
! Helpers::is_enhanced_measurement_enabled( 'revenue', $enhanced_measurements ) &&
! Helpers::is_enhanced_measurement_enabled( 'search', $enhanced_measurements ) ) {
return; // @codeCoverageIgnore
}

Expand All @@ -292,6 +312,15 @@ public function maybe_create_custom_properties( $old_settings, $settings ) {
}
}

/**
* Create Custom Properties for Search Queries option.
*/
if ( Helpers::is_enhanced_measurement_enabled( 'search', $enhanced_measurements ) ) {
foreach ( $this->custom_search_properties as $property ) {
$properties[] = new Client\Model\CustomProp( [ 'custom_prop' => [ 'key' => $property ] ] );
}
}

$create_request->setCustomProps( $properties );

$this->client->enable_custom_property( $create_request );
Expand Down
26 changes: 2 additions & 24 deletions src/Admin/Settings/Hooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ public function __construct( $init = true ) {
*/
private function init_hooks() {
add_filter( 'plausible_analytics_toggle_option_success_message', [ $this, 'maybe_modify_success_message' ], 10, 3 );
add_action( 'plausible_analytics_settings_api_connect_button', [ $this, 'connect_button' ] );
add_action( 'plausible_analytics_settings_api_token_missing', [ $this, 'missing_api_token_warning' ] );
add_action( 'plausible_analytics_settings_option_not_available_in_ce', [ $this, 'option_na_in_ce' ] );
add_action( 'plausible_analytics_settings_proxy_warning', [ $this, 'proxy_warning' ] );
add_action( 'plausible_analytics_settings_enable_analytics_dashboard_notice', [ $this, 'enable_analytics_dashboard_notice' ] );
add_action( 'plausible_analytics_settings_option_disabled_by_missing_api_token', [ $this, 'option_disabled_by_missing_api_token' ] );
add_action( 'plausible_analytics_settings_option_disabled_by_proxy', [ $this, 'option_disabled_by_proxy' ] );
add_action( 'plausible_analytics_settings_option_not_available_in_ce', [ $this, 'option_na_in_ce' ] );
add_action( 'plausible_analytics_settings_proxy_warning', [ $this, 'proxy_warning' ] );
}

/**
Expand All @@ -63,27 +62,6 @@ public function maybe_modify_success_message( $message, $option_name, $status )
return __( 'Proxy enabled.', 'plausible-analytics' );
}

/**
* Display connect button.
*
* @output HTML
*/
public function connect_button() {
$settings = Helpers::get_settings();

if ( ! empty( $settings[ 'domain_name' ] ) && ! empty( $settings[ 'api_token' ] ) ): ?>

<?php else: ?>
<?php
$url = sprintf( '%s/%s/settings/integrations?new_token=Wordpress', Helpers::get_hosted_domain_url(), Helpers::get_domain() );
?>
<a href="<?php esc_attr_e( $url, 'plausible-analytics' ); ?>" target="_blank" class="plausible-analytics-btn">
<?php esc_html_e( 'Connect to Plausible', 'plausible-analytics' ); ?>
</a>
<?php endif; ?>
<?php
}

/**
* Renders the warning for the Enable Proxy option.
*
Expand Down
9 changes: 8 additions & 1 deletion src/Admin/Settings/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,13 @@ public function __construct() {
'type' => 'checkbox',
'value' => 'file-downloads',
],
'search' => [
'label' => esc_html__( 'Search queries', 'plausible-analytics' ),
'docs' => 'https://plausible.io/wordpress-analytics-plugin#how-to-enable-site-search-tracking',
'slug' => 'enhanced_measurements',
'type' => 'checkbox',
'value' => 'search',
],
'tagged-events' => [
'label' => esc_html__( 'Custom events', 'plausible-analytics' ),
'docs' => 'https://plausible.io/wordpress-analytics-plugin#how-to-setup-custom-events-to-track-goal-conversions',
Expand Down Expand Up @@ -649,7 +656,7 @@ public function render_analytics_dashboard() {
<div id="plausible-analytics-stats">
<iframe plausible-embed=""
src="<?php echo "{$shared_link}&embed=true&theme=light&background=transparent"; ?>"
scrolling="no" loading="lazy" style="border: 0; width: 100%; height: 1750px; "></iframe>
loading="lazy" style="border: 0; width: 100%; height: 1750px; "></iframe>
<script async src="<?php echo $hosted_domain; ?>/js/embed.host.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function add_plausible_attributes( $tag, $handle ) {

$settings = Helpers::get_settings();
$api_url = Helpers::get_data_api_url();
$domain_name = esc_html( $settings[ 'domain_name' ] );
$domain_name = Helpers::get_domain();

// We need the correct id attribute for IE compatibility.
$tag = preg_replace( "/\sid=(['\"])plausible-analytics-js(['\"])/", " id=$1plausible$2", $tag );
Expand Down
18 changes: 14 additions & 4 deletions src/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,21 @@ public static function get_filename( $local = false ) {
if ( ! self::is_enhanced_measurement_enabled( 'tagged-events' ) &&
self::is_enhanced_measurement_enabled( 'revenue' ) &&
( Integrations::is_wc_active() || Integrations::is_edd_active() ) ) {
$file_name .= '.' . 'tagged-events';
$file_name .= '.tagged-events';
}

if ( ! self::is_enhanced_measurement_enabled( 'pageview-props' ) && self::is_enhanced_measurement_enabled( 'search' ) ) {
$file_name .= '.pageview-props'; // @codeCoverageIgnore
}

// Load exclusions.js if any excluded pages are set.
if ( ! empty( $settings[ 'excluded_pages' ] ) ) {
$file_name .= '.' . 'exclusions';
$file_name .= '.exclusions';
}

// Add the manual scripts as we need it to track the search parameter.
if ( self::is_enhanced_measurement_enabled( 'search' ) ) {
$file_name .= '.manual'; // @codeCoverageIgnore
}

return $file_name;
Expand Down Expand Up @@ -303,7 +312,7 @@ public static function get_domain() {

$url = home_url();

return preg_replace( '/^http(s?)\:\/\/(www\.)?/i', '', $url );
return preg_replace( '/^http(s?):\/\/(www\.)?/i', '', $url );
}

/**
Expand All @@ -312,10 +321,11 @@ public static function get_domain() {
* @since 1.2.2
* @access public
* @return string
* @throws Exception
*/
public static function get_data_api_url() {
if ( self::proxy_enabled() ) {
// This'll make sure the API endpoint is properly registered when we're testing.
// This will make sure the API endpoint is properly registered when we're testing.
$append = isset( $_GET[ 'plausible_proxy' ] ) ? '?plausible_proxy=1' : '';

return self::get_rest_endpoint() . $append;
Expand Down
10 changes: 9 additions & 1 deletion tests/integration/Admin/ProvisioningTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function testCreateGoals() {
'404',
'outbound-links',
'file-downloads',
'search',
];
$mock = $this->getMockBuilder( Client::class )->onlyMethods( [ 'create_goals' ] )->getMock();
$goals_array = [
Expand All @@ -75,6 +76,12 @@ public function testCreateGoals() {
'goal_type' => 'Goal.CustomEvent',
]
),
new Goal(
[
'goal' => new GoalPageviewAllOfGoal( [ 'display_name' => 'Search', 'id' => 444, 'path' => null ] ),
'goal_type' => 'Goal.Pageview',
]
),
];
$goals = new Client\Model\GoalListResponse();

Expand All @@ -88,10 +95,11 @@ public function testCreateGoals() {

$goal_ids = get_option( 'plausible_analytics_enhanced_measurements_goal_ids' );

$this->assertCount( 3, $goal_ids );
$this->assertCount( 4, $goal_ids );
$this->assertArrayHasKey( 111, $goal_ids );
$this->assertArrayHasKey( 222, $goal_ids );
$this->assertArrayHasKey( 333, $goal_ids );
$this->assertArrayHasKey( 444, $goal_ids );

delete_option( 'plausible_analytics_enhanced_measurements_goal_ids' );
}
Expand Down
21 changes: 21 additions & 0 deletions tests/integration/HelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ public function testGetFilename() {
remove_filter( 'plausible_analytics_integrations_woocommerce', '__return_true' );

$this->assertEquals( 'plausible.revenue.tagged-events', $filename );

add_filter( 'plausible_analytics_settings', [ $this, 'enableSearch' ] );

$filename = Helpers::get_filename();

$this->assertEquals( 'plausible.pageview-props.manual', $filename );

remove_filter( 'plausible_analytics_settings', [ $this, 'enablePageviewProps' ] );
}

/**
Expand Down Expand Up @@ -127,6 +135,19 @@ public function enableRevenue( $settings ) {
return $settings;
}

/**
* Enable Enhanced Measurements > Search Queries
*
* @param $settings
*
* @return mixed
*/
public function enableSearch( $settings ) {
$settings[ 'enhanced_measurements' ] = [ 'search' ];

return $settings;
}

/**
* @see Helpers::get_settings()
*
Expand Down