Skip to content

Commit 3d71316

Browse files
authored
Merge pull request #213 from plausible/track_search_events
Added: Search Queries option, which allows tracking of search events.
2 parents 94e324b + 951fc93 commit 3d71316

File tree

8 files changed

+115
-35
lines changed

8 files changed

+115
-35
lines changed

src/Actions.php

+29-2
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,38 @@ public function maybe_register_assets() {
6666
);
6767

6868
// Track 404 pages (if enabled)
69-
if ( is_array( $settings[ 'enhanced_measurements' ] ) && in_array( '404', $settings[ 'enhanced_measurements' ] ) && is_404() ) {
69+
if ( Helpers::is_enhanced_measurement_enabled( '404' ) && is_404() ) {
70+
$data = wp_json_encode(
71+
[
72+
'props' => [
73+
'path' => 'documentation.location.pathname',
74+
],
75+
]
76+
);
77+
7078
wp_add_inline_script(
7179
'plausible-analytics',
72-
"document.addEventListener('DOMContentLoaded', function () { plausible('404', { props: { path: document.location.pathname } }); });"
80+
"document.addEventListener('DOMContentLoaded', function () { plausible( '404', $data ); });"
81+
);
82+
}
83+
84+
// 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.
85+
if ( Helpers::is_enhanced_measurement_enabled( 'search' ) && is_search() ) {
86+
global $wp_rewrite, $wp_query;
87+
88+
$search_url = str_replace( '%search%', '', get_site_url( null, $wp_rewrite->get_search_permastruct() ) );
89+
$data = wp_json_encode(
90+
[
91+
'props' => [
92+
'search_query' => get_search_query(),
93+
'result_count' => $wp_query->found_posts,
94+
],
95+
]
7396
);
97+
$script = 'plausible("pageview", {u:"' . esc_attr( $search_url ) . '"});';
98+
$script .= "\nplausible('Search', $data );";
99+
100+
wp_add_inline_script( 'plausible-analytics', "document.addEventListener('DOMContentLoaded', function() {\n$script\n});" );
74101
}
75102

76103
// This action allows you to add your own custom scripts!

src/Admin/Provisioning.php

+31-2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ class Provisioning {
3535
'category',
3636
];
3737

38+
private $custom_search_properties = [
39+
'search_query',
40+
'result_count',
41+
];
42+
3843
/**
3944
* Build class.
4045
*
@@ -63,6 +68,7 @@ public function __construct( $client = null ) {
6368
'404' => __( '404', 'plausible-analytics' ),
6469
'outbound-links' => __( 'Outbound Link: Click', 'plausible-analytics' ),
6570
'file-downloads' => __( 'File Download', 'plausible-analytics' ),
71+
'search' => __( 'Search', 'plausible-analytics' ),
6672
];
6773

6874
$this->init();
@@ -140,6 +146,13 @@ public function maybe_create_goals( $old_settings, $settings ) {
140146
}
141147

142148
$goals[] = $this->create_request_custom_event( $this->custom_event_goals[ $measurement ] );
149+
150+
if ( $measurement === 'search' ) {
151+
global $wp_rewrite;
152+
153+
$search_url = str_replace( '%search%', '', $wp_rewrite->get_search_permastruct() );
154+
$goals[] = $this->create_request_custom_event( null, 'Pageview', '', $search_url );
155+
}
143156
}
144157

145158
$this->create_goals( $goals );
@@ -152,7 +165,7 @@ public function maybe_create_goals( $old_settings, $settings ) {
152165
*
153166
* @return GoalCreateRequestCustomEvent
154167
*/
155-
private function create_request_custom_event( $name, $type = 'CustomEvent', $currency = '' ) {
168+
private function create_request_custom_event( $name, $type = 'CustomEvent', $currency = '', $path = '' ) {
156169
$props = [
157170
'goal' => [
158171
'event_name' => $name,
@@ -164,6 +177,12 @@ private function create_request_custom_event( $name, $type = 'CustomEvent', $cur
164177
$props[ 'goal' ][ 'currency' ] = $currency;
165178
}
166179

180+
if ( $type === 'Pageview' ) {
181+
unset( $props[ 'goal' ][ 'event_name' ] );
182+
183+
$props[ 'goal' ][ 'path' ] = $path;
184+
}
185+
167186
return new Client\Model\GoalCreateRequestCustomEvent( $props );
168187
}
169188

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

269288
if ( ! Helpers::is_enhanced_measurement_enabled( 'pageview-props', $enhanced_measurements ) &&
270-
! Helpers::is_enhanced_measurement_enabled( 'revenue', $enhanced_measurements ) ) {
289+
! Helpers::is_enhanced_measurement_enabled( 'revenue', $enhanced_measurements ) &&
290+
! Helpers::is_enhanced_measurement_enabled( 'search', $enhanced_measurements ) ) {
271291
return; // @codeCoverageIgnore
272292
}
273293

@@ -292,6 +312,15 @@ public function maybe_create_custom_properties( $old_settings, $settings ) {
292312
}
293313
}
294314

315+
/**
316+
* Create Custom Properties for Search Queries option.
317+
*/
318+
if ( Helpers::is_enhanced_measurement_enabled( 'search', $enhanced_measurements ) ) {
319+
foreach ( $this->custom_search_properties as $property ) {
320+
$properties[] = new Client\Model\CustomProp( [ 'custom_prop' => [ 'key' => $property ] ] );
321+
}
322+
}
323+
295324
$create_request->setCustomProps( $properties );
296325

297326
$this->client->enable_custom_property( $create_request );

src/Admin/Settings/Hooks.php

+2-24
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,12 @@ public function __construct( $init = true ) {
3333
*/
3434
private function init_hooks() {
3535
add_filter( 'plausible_analytics_toggle_option_success_message', [ $this, 'maybe_modify_success_message' ], 10, 3 );
36-
add_action( 'plausible_analytics_settings_api_connect_button', [ $this, 'connect_button' ] );
3736
add_action( 'plausible_analytics_settings_api_token_missing', [ $this, 'missing_api_token_warning' ] );
38-
add_action( 'plausible_analytics_settings_option_not_available_in_ce', [ $this, 'option_na_in_ce' ] );
39-
add_action( 'plausible_analytics_settings_proxy_warning', [ $this, 'proxy_warning' ] );
4037
add_action( 'plausible_analytics_settings_enable_analytics_dashboard_notice', [ $this, 'enable_analytics_dashboard_notice' ] );
4138
add_action( 'plausible_analytics_settings_option_disabled_by_missing_api_token', [ $this, 'option_disabled_by_missing_api_token' ] );
4239
add_action( 'plausible_analytics_settings_option_disabled_by_proxy', [ $this, 'option_disabled_by_proxy' ] );
40+
add_action( 'plausible_analytics_settings_option_not_available_in_ce', [ $this, 'option_na_in_ce' ] );
41+
add_action( 'plausible_analytics_settings_proxy_warning', [ $this, 'proxy_warning' ] );
4342
}
4443

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

66-
/**
67-
* Display connect button.
68-
*
69-
* @output HTML
70-
*/
71-
public function connect_button() {
72-
$settings = Helpers::get_settings();
73-
74-
if ( ! empty( $settings[ 'domain_name' ] ) && ! empty( $settings[ 'api_token' ] ) ): ?>
75-
76-
<?php else: ?>
77-
<?php
78-
$url = sprintf( '%s/%s/settings/integrations?new_token=Wordpress', Helpers::get_hosted_domain_url(), Helpers::get_domain() );
79-
?>
80-
<a href="<?php esc_attr_e( $url, 'plausible-analytics' ); ?>" target="_blank" class="plausible-analytics-btn">
81-
<?php esc_html_e( 'Connect to Plausible', 'plausible-analytics' ); ?>
82-
</a>
83-
<?php endif; ?>
84-
<?php
85-
}
86-
8765
/**
8866
* Renders the warning for the Enable Proxy option.
8967
*

src/Admin/Settings/Page.php

+8-1
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,13 @@ public function __construct() {
153153
'type' => 'checkbox',
154154
'value' => 'file-downloads',
155155
],
156+
'search' => [
157+
'label' => esc_html__( 'Search queries', 'plausible-analytics' ),
158+
'docs' => 'https://plausible.io/wordpress-analytics-plugin#how-to-enable-site-search-tracking',
159+
'slug' => 'enhanced_measurements',
160+
'type' => 'checkbox',
161+
'value' => 'search',
162+
],
156163
'tagged-events' => [
157164
'label' => esc_html__( 'Custom events', 'plausible-analytics' ),
158165
'docs' => 'https://plausible.io/wordpress-analytics-plugin#how-to-setup-custom-events-to-track-goal-conversions',
@@ -649,7 +656,7 @@ public function render_analytics_dashboard() {
649656
<div id="plausible-analytics-stats">
650657
<iframe plausible-embed=""
651658
src="<?php echo "{$shared_link}&embed=true&theme=light&background=transparent"; ?>"
652-
scrolling="no" loading="lazy" style="border: 0; width: 100%; height: 1750px; "></iframe>
659+
loading="lazy" style="border: 0; width: 100%; height: 1750px; "></iframe>
653660
<script async src="<?php echo $hosted_domain; ?>/js/embed.host.js"></script>
654661
<script>
655662
document.addEventListener('DOMContentLoaded', () => {

src/Filters.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public function add_plausible_attributes( $tag, $handle ) {
5050

5151
$settings = Helpers::get_settings();
5252
$api_url = Helpers::get_data_api_url();
53-
$domain_name = esc_html( $settings[ 'domain_name' ] );
53+
$domain_name = Helpers::get_domain();
5454

5555
// We need the correct id attribute for IE compatibility.
5656
$tag = preg_replace( "/\sid=(['\"])plausible-analytics-js(['\"])/", " id=$1plausible$2", $tag );

src/Helpers.php

+14-4
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,21 @@ public static function get_filename( $local = false ) {
6363
if ( ! self::is_enhanced_measurement_enabled( 'tagged-events' ) &&
6464
self::is_enhanced_measurement_enabled( 'revenue' ) &&
6565
( Integrations::is_wc_active() || Integrations::is_edd_active() ) ) {
66-
$file_name .= '.' . 'tagged-events';
66+
$file_name .= '.tagged-events';
67+
}
68+
69+
if ( ! self::is_enhanced_measurement_enabled( 'pageview-props' ) && self::is_enhanced_measurement_enabled( 'search' ) ) {
70+
$file_name .= '.pageview-props'; // @codeCoverageIgnore
6771
}
6872

6973
// Load exclusions.js if any excluded pages are set.
7074
if ( ! empty( $settings[ 'excluded_pages' ] ) ) {
71-
$file_name .= '.' . 'exclusions';
75+
$file_name .= '.exclusions';
76+
}
77+
78+
// Add the manual scripts as we need it to track the search parameter.
79+
if ( self::is_enhanced_measurement_enabled( 'search' ) ) {
80+
$file_name .= '.manual'; // @codeCoverageIgnore
7281
}
7382

7483
return $file_name;
@@ -303,7 +312,7 @@ public static function get_domain() {
303312

304313
$url = home_url();
305314

306-
return preg_replace( '/^http(s?)\:\/\/(www\.)?/i', '', $url );
315+
return preg_replace( '/^http(s?):\/\/(www\.)?/i', '', $url );
307316
}
308317

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

321331
return self::get_rest_endpoint() . $append;

tests/integration/Admin/ProvisioningTest.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ public function testCreateGoals() {
5454
'404',
5555
'outbound-links',
5656
'file-downloads',
57+
'search',
5758
];
5859
$mock = $this->getMockBuilder( Client::class )->onlyMethods( [ 'create_goals' ] )->getMock();
5960
$goals_array = [
@@ -75,6 +76,12 @@ public function testCreateGoals() {
7576
'goal_type' => 'Goal.CustomEvent',
7677
]
7778
),
79+
new Goal(
80+
[
81+
'goal' => new GoalPageviewAllOfGoal( [ 'display_name' => 'Search', 'id' => 444, 'path' => null ] ),
82+
'goal_type' => 'Goal.Pageview',
83+
]
84+
),
7885
];
7986
$goals = new Client\Model\GoalListResponse();
8087

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

8996
$goal_ids = get_option( 'plausible_analytics_enhanced_measurements_goal_ids' );
9097

91-
$this->assertCount( 3, $goal_ids );
98+
$this->assertCount( 4, $goal_ids );
9299
$this->assertArrayHasKey( 111, $goal_ids );
93100
$this->assertArrayHasKey( 222, $goal_ids );
94101
$this->assertArrayHasKey( 333, $goal_ids );
102+
$this->assertArrayHasKey( 444, $goal_ids );
95103

96104
delete_option( 'plausible_analytics_enhanced_measurements_goal_ids' );
97105
}

tests/integration/HelpersTest.php

+21
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,14 @@ public function testGetFilename() {
8686
remove_filter( 'plausible_analytics_integrations_woocommerce', '__return_true' );
8787

8888
$this->assertEquals( 'plausible.revenue.tagged-events', $filename );
89+
90+
add_filter( 'plausible_analytics_settings', [ $this, 'enableSearch' ] );
91+
92+
$filename = Helpers::get_filename();
93+
94+
$this->assertEquals( 'plausible.pageview-props.manual', $filename );
95+
96+
remove_filter( 'plausible_analytics_settings', [ $this, 'enablePageviewProps' ] );
8997
}
9098

9199
/**
@@ -127,6 +135,19 @@ public function enableRevenue( $settings ) {
127135
return $settings;
128136
}
129137

138+
/**
139+
* Enable Enhanced Measurements > Search Queries
140+
*
141+
* @param $settings
142+
*
143+
* @return mixed
144+
*/
145+
public function enableSearch( $settings ) {
146+
$settings[ 'enhanced_measurements' ] = [ 'search' ];
147+
148+
return $settings;
149+
}
150+
130151
/**
131152
* @see Helpers::get_settings()
132153
*

0 commit comments

Comments
 (0)