I need to be able to track UTM parameters in Google Analytics without them being in the URL.
We load information when the page loads, and we want to use this information in our UTM parameters, and we don't want to redirect users to the URL with UTM variables appended.
I see on this page you can call a pageview with javascript, but I don't see anyway to specify utm parameters: https://developers.google.com/analytics/devguides/collection/analyticsjs/pages.
I simply used the Google gtag.js documentation on PageViews to edit the script that loads the inital pageview information.
I first pull the current URL and append the variables to the end of the URL, and pass the new URL as the pageview to override the URL without the UTM parameters.
I am using laravel so #if statements will work within the JS, and {{}} is echoing the variables.
<script>
var url = new URL( window.location.href );
#if( isset( $request->utm_source ) )
url.searchParams.set( 'utm_medium', '{{ strtolower( $request->utm_source ) }}' );
#endif
#if( isset( $request->utm_medium ) )
url.searchParams.set( 'utm_medium', '{{ strtolower( $request->utm_medium ) }}' );
#endif
#if( isset( $request->utm_campaign ) )
url.searchParams.set( 'utm_campaign', '{{ strtolower( $request->utm_campaign ) }}' );
#endif
#if( isset( $request->utm_term ) )
url.searchParams.set( 'utm_term', '{{ strtolower( $request->utm_term ) }}' );
#endif
#if( isset( $request->utm_content ) )
url.searchParams.set( 'utm_content', '{{ strtolower( $request->utm_content ) }}' );
#endif
function gtag() {
dataLayer.push(arguments)
}
window.dataLayer = window.dataLayer || [], gtag("js", new Date), gtag("config", "GA_MEASUREMENT_ID", {
'page_title': document.title,
'page_location': url.href
});
</script>
Related
I am trying to send out emails to my customers and allow them one click to reset passwords with their email pre-filled on the reset password page by URL /account/lost-password/?email=123#gmail.com
However, I am not sure how to make it right. Here is my code. Thanks!
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
if ( isset( $_GET['email'] ) ) {
$em = isset( $_GET['email'] ) ? esc_attr( $_GET['email'] ) : '';
// Set the session data
WC()->session->set( 'custom_data', array( 'email' => $em ) );
}
}
add_filter( 'woocommerce_login_form' , 'prefill_login_form' );
function prefill_login_form ( $fields ) {
// Get the session data
$data = WC()->session->get('custom_data');
// Email
if( isset($data['email']) && ! empty($data['email']) )
$fields['user_login']['default'] = $data['email'];
return $fields;
}
I managed to do it by referencing this thread
Pre-fill Woocommerce login fields with URL variables saved in session
<?php
add_action('woocommerce_lostpassword_form','woocommerce_js_2');
function woocommerce_js_2()
{ // break out of php
?>
<script>
// Setup a document ready to run on initial load
jQuery(document).ready(function($) {
//var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b
var r = /[?|&](\w+)=([\w.-]+#[\w.-]+)/g;
var query = r.exec(window.location.href); //gets the first query from the url
while (query != null) {
//index 0=whole match, index 1=first group(key) index 2=second group(value)
$("input[name="+ query[1] +"]").attr("value",query[2]);
query = r.exec(window.location.href); //repeats to get next capture
}
});
</script>
<?php } // break back into php
I've created a shortcode that always me to use a URL parameter to dynamically swap the featured product on the home page which works well:
// Shortcode to display specific product page via URL - ?myppid=46
// =============================================================================
function ppid_from_query( $atts ) {
$atts = shortcode_atts( array(
'default' => 46
), $atts, 'myppid' );
$pp_id = $atts['default'];
if ( isset( $_REQUEST['ppid'] ) && $_REQUEST['ppid'] != '' ) {
$pp_id = intval( $_REQUEST['ppid'] );
}
return do_shortcode( "[product_page id='".$pp_id."']" );
}
add_shortcode( 'myppid', 'ppid_from_query' );
The challenge I'm having, is that if the user goes to any other page on my site and returns, the URL parameter is gone, and the default product shows up.
I've tried several methods for passing the parameter, but have not succeeded... Even if I had, it would have worked for that session only. In other words, if user leaves site and comes back to primary domain without ?ppid=X, then they won't see that product. So to that end, I've tried setting a cookie per this thread I found (granted it's a bit dated): https://wordpress.stackexchange.com/questions/188749/i-am-looking-to-append-url-parameter-to-all-urls
So in my header, I have:
<script>
if(!isset($_SESSION['ppid']) and $_GET['ppid']){
$cookie_expire = time()+60*60*24*30;
$_SESSION['ppid'] = $_GET['ppid'];
setcookie('ppid', $_SESSION['ppid'], $cookie_expire, '/', '.'.$_SERVER['HTTP_HOST']);
</script>
and in functions:
function wprdcv_param_redirect(){
if(isset($_COOKIE['ppid']) and !$_GET['ppid']){
$location = esc_url(add_query_arg('ppid', $_COOKIE['ppid']));
wp_redirect($location);
}
}
add_action('template_redirect', 'wprdcv_param_redirect');
Still no luck. What am I doing wrong?
The PHP code is processed by the web server and not by the browser. You don't have to set the cookie between the <script> tags. Instead, run it via the Wordpress init hook.
Based on #MattMelton's comment I added the checkout page exclusion in the wprdcv_param_redirect function.
You can optimize your functions like this:
add_shortcode( 'myppid', 'ppid_from_query' );
function ppid_from_query( $atts ) {
$atts = shortcode_atts( array(
'default' => 46
), $atts, 'myppid' );
$pp_id = $atts['default'];
if ( isset( $_REQUEST['ppid'] ) && $_REQUEST['ppid'] != '' ) {
$pp_id = intval( $_REQUEST['ppid'] );
}
return do_shortcode( "[product_page id='".$pp_id."']" );
}
// set the cookie based on the url parameter "ppid"
add_action( 'init', 'set_cookie_based_on_url_parameter_ppid' );
function set_cookie_based_on_url_parameter_ppid() {
if ( ! isset($_SESSION['ppid'] ) && $_GET['ppid'] ) {
$cookie_expire = time()+60*60*24*30;
$_SESSION['ppid'] = $_GET['ppid'];
setcookie('ppid', $_SESSION['ppid'], $cookie_expire, '/', '.'.$_SERVER['HTTP_HOST']);
}
}
add_action('template_redirect', 'wprdcv_param_redirect');
function wprdcv_param_redirect(){
// if it's the checkout page, don't redirect
if ( is_checkout() ) {
return;
}
/*
// if it is the order confirmation page in checkout, please do not redirect
if ( is_checkout() && is_wc_endpoint_url( 'order-received' ) ) {
return;
}
*/
if ( isset($_COOKIE['ppid']) && ! $_GET['ppid'] ) {
$location = esc_url( add_query_arg('ppid', $_COOKIE['ppid']) );
wp_redirect($location);
}
}
The code has been tested and works for me. Add it to your active theme's functions.php.
I want to change the #type: Article exported by the WordLift plugin in JSON-LD to #type: NewsArticle.
How can I do that?
You can filter the JSON-LD output before it is sent to the client and change any part of it, e.g. in this specific case:
add_filter( 'wl_post_jsonld', function( $jsonld ) {
// Bail out if `#type` isn't set or isn't `Article`.
if ( ! isset( $jsonld['#type'] ) || 'Article' !== $jsonld['#type'] ) {
return $jsonld;
}
$jsonld['#type'] = 'NewsArticle';
return $jsonld;
} );
I'm teaching myself how to build Wordpress plugins. I found a great guide to creating a Wordpress Meta Box and saving the form input from it.
https://themefoundation.com/wordpress-meta-boxes-guide/
I want to send the entered and saved form input from the Meta Box that is in the Post edit view of Wordpress to the Wordpress RSS in its own tag. So when the user publishes the Post the Meta Box form data saves and adds the saved input to the post Wordpress RSS.
This is the code that saves the form input:
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
I figured out the code to add to the above tutorial article about creating a Meta Box that saves values. This code puts the post meta into its own tag in the RSS. I added the post meta "meta-text" to the code below to work with the tutorial.
add_action('rss2_item', 'add_my_custom_field_node');
function add_my_custom_field_node() {
global $post;
$metaValue = get_post_meta($post->ID, 'meta-text', true);
if(!empty($metaValue)):
echo("<my-custom-field>{$metaValue}</my-custom-field>");
endif;
}
So there are people who access my website directly (not thru the tracking link I got with Voluum), thus they are not able to click the links and I can't see them as a part of my stats.
How can I redirect users who don't have a /?voluumdata=BASE64... URL parameter to a tracked URL, and to have a different redirect for each blog post?
I was testing and looking for a plugin / .htaccess trick for hours but nothing seemed to help.
Edit: I found a solution that I was certain is going to work but for some reason it didn't:
[insert_php]
if(empty($_GET['voluumdata']))
{
header('Location: REDIRECT_URL');
exit;
}
[/insert_php]
Also tried:
[insert_php]
if(!isset($_GET['voluumdata']))
{
header('Location: REDIRECT_URL');
exit;
}
[/insert_php]
Both just break the page loading proccess.
Unfortunately, I cannot understand what is the purpose of the code you have entered in your question. I mean that is not clear the reason you use the tags [insert_php].
A solution to your problem it can be the following.
function redirect_direct_access( ) {
// You may use the code:
//
// global $wp_query
//
// in order to determine in which pages you should run your
// redirection code. If you only check for the token existence
// then you will be faced with redirection loop. I don't explain in
// depth how to use the $wp_query as it is not part of your question
// but you always have the opportunity to check what is the contents
// of this variable using the code:
//
// echo "<pre>";
// print_r( $wp_query );
// echo "</pre>";
//
// This way you will be able to build your specific if statement
// for the page you like to test.
if (
! isset( $_GET[ 'voluumdata' ] ) ||
empty( $_GET[ 'voluumdata' ] )
) {
wp_redirect( home_url( '/page/to/redirect/' ) );
exit();
}
}
add_action( 'template_redirect', 'redirect_direct_access' );
You can find more information in the WordPress documentation related to the template_redirect hook.
Just in case anyone would face the same issue, #Merianos Nikos has given a half-answer and I mastered it into this:
function redirect_direct_access( ) {
$post_id = get_the_ID();
if (
$post_id == POST_ID &&
!isset( $_GET[ 'voluumdata' ] )
) {
wp_redirect( 'REDIRECT_URL' );
exit();
}
if (
$post_id == POST_ID &&
!isset( $_GET[ 'voluumdata' ] )
) {
wp_redirect( 'REDIRECT_URL' );
exit();
}
}
add_action( 'template_redirect', 'redirect_direct_access' );