Can't correctly see Custom Events in GA4's Debug View - wordpress

I'm working on a WordPress site and in order to have a custom tracking, I've tried a bunch of things but always encounter issues no matter what.
So it's an eShop (WooCommerce) and to start my tracking, I just try as a first step to add the Product Name as a custom parameter in my custom events.
Firstly, I tried to create a tag in GTM which uses a custom variable that gets its value from a data layer pushed in a JS file enqueued in my child theme.
Here's how I enqueued and populated the script, at the end of a function I called "tracking_process" :
wp_register_script('data_layer', get_stylesheet_directory_uri() . '/scripts/tracking.js', array('jquery'), null, false );
// "data" contains my product name
wp_add_inline_script('data_layer', 'var data = ' . wp_json_encode($data), 'after');
And here's the action :
add_action('wp_footer', 'tracking_process');
The script correctly loads on the page.
The product name is correctly sent to the script.
The data layer is correctly pushed as I can see in the Tag Assistant my product name in the data layer tab.
The issue is...
My data layer seems to be pushed after the tag is sent to GA4, resulting in my custom parameter always being empty in the custom event, in the Debug View.
add_action('wp_enqueue_scripts', 'tracking_process', 0);
I also tried something I found on another thread, to put the script at the beginning of the queue :
(I execute this line after "wp_register_script")
array_unshift(wp_scripts()->queue, 'data_layer');
All of this without any success, my data layer is always pushed after my tag is triggered.
So I tried another approach...
I tried to send my custom event directly from the JS file.
jQuery(document).ready( function() {
gtag('event', 'test_product', {
'product_name' : data.product_name,
});
});
Half of the time, the custom event doesn't show up in the Debug View, without any apparent reason.
When it does, it seems the "page_view" automatic event doesn't trigger.
And when I don't see the custom event, "page_view" shows up instead.
Note that in Tag Assistant, I always correctly see my custom event, so I really don't get why it doesn't in the Debug View.
The issue persists even after 48h (I've seen there can be some delay).
And that's a staging site, there's no traffic on it. The live site is brand new and has low traffic as well at the moment.
The complete PHP function :
function tracking_process(){
global $product;
if( is_product() ) {
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_id() );
}
$product_name = $product->get_name();
$data['product_name'] = $product_name;
}
wp_register_script('data_layer', get_stylesheet_directory_uri() . '/scripts/tracking.js', array('jquery'), null, false );
array_unshift(wp_scripts()->queue, 'data_layer');
wp_add_inline_script('data_layer', 'var data = ' . wp_json_encode($data), 'after');
};
add_action('wp_enqueue_scripts', 'tracking_process', 0);
I searched a lot online but found nothing that fixed this issue, and even tried with ChatGPT by giving him precise details but nothing worked so far.
Also note that I already created the custom dimensions in GA4 so it recognizes my custom parameters, and that I don't get any error in the console.
Anyone having an idea of how I can fix this issue ?
Thanks in advance !

Related

Wordpress Shortcode Output Buffering Renders Content When Saving Post in WP Admin

I have a WP shortcode that is giving me problems.
Basically, the shortcode just pulls content from another post using a couple of parameters. It then loads up a partial template.
The problem occurs in WP Admin when saving the page that contains the shortcode. When saving the page updates do in fact save correctly but the resulting page is a page that outputs the contents of the shortcode.
I'm using output buffering around get_template_part() for two reasons: 1. So I only have one instance of the template in my code - and - 2. Because the template is actually pretty substantial and appending all of it to an output variable would be a daunting task.
The shortcode works fine in every way except when saving the page.
Here is a video demonstrating the issue:
https://www.awesomescreenshot.com/video/1146323?key=103ae00d841b47cee8a902eb18c8988a
Here is my code:
function get_main_page_content( $atts ) {
$main_page_id = $atts['main_page_id'];
$section = $atts['section'];
$people_display_option = $atts['people_display_option'];
$GLOBALS['sc_display_option'] = $people_display_option;
ob_start();
if(have_rows('flexible_content', $main_page_id)):
while(have_rows('flexible_content', $main_page_id)): the_row();
if ( $section == 'agenda' ) {
get_template_part('partials/agenda');
}
if ( $section == 'people_cards' ) {
get_template_part('partials/people-cards');
}
endwhile;
endif;
ob_end_flush();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode('get_main_page_content', 'get_main_page_content');
It looks to me like ob_end_flush() is not needed and is redundant. That might be causing the OB to send twice, resulting in that code on your screen.
I'd be curious if your problem persists if you drop that line. Also, for a very simplified version of your exact usecase, check this blog post:
https://konstantin.blog/2013/get_template_part-within-shortcodes

Wordpress: Can I use get_post_meta in my Plugin?

So I'm trying to reference custom field values in a plugin I'm building. All I need to do at this stage is grab the values and store them in variables. This is my code to get the custom field value of pageName:
<?php
global $wp_query;
$postid = $wp_query->post->ID;
$pageName = get_post_meta($postid, 'pageName', true);
wp_reset_query()
?>
So when I try to echo that out, I get nothing. I notice that my plugin runs before the head or anything else, so it's the first code in the source. My hunch is that this is due to timing and the value just isn't there yet. Is there a way to make my plugin, or this chunk of code, wait until the custom field values are there before trying to grab them?
I'm trying to avoid doing anything in the theme files so this can be a stand alone plugin that I can share.
yes, you can get the value of any post meta of the custom post type.
Just make sure that you are receiving the correct post_id in the $postid variable.
If you get the correct id of the post type you can get any meta field
Example:
global $post;
if ($post->ID) {
$media_id_meta = get_post_meta($post->ID, 'media_id', true);
}
Found the solution! I wrapped the whole thing in a function to put it in the footer, which made sure that everything it needed was there.
//----This function is wrapped around the code for my plugin
function dataLayerInject() {
*ALL MY CODE*
}
//----This drops my code into the footer
add_action('wp_footer', 'dataLayerInject');

How do I get the current page in Gravity Forms

How do I get the current page of a multi page form in Gravity Forms? I've got two solutions that sort of work but neither fully work.
function gf_get_current_page() {
return rgpost( 'gform_source_page_number_' . $_POST['gform_submit'] ) ? rgpost( 'gform_target_page_number_' . $_POST['gform_submit'] ) : 1;
}
This solution works until someone doesn't fill out a required field before hitting the next button. Then it says the user is on page 3 even though they're still on page 2 and need to fix validation errors.
add_action( 'gform_post_paging', 'get_current_page_num_gf', 10, 3 );
function get_current_page_num_gf( $form, $source_page_number, $current_page_number ) {
echo '<script type="text/javascript">console.log(\'' . $current_page_number . '\');</script>';
}
This works well until the validation errors again. In this scenario, instead of changing the page number, it just outputs nothing.
I'd like to know what page the user is on at all times. If they miss a required question on step 2, then I'd like to know that they're still on step 2.
In the end, I'm hoping to send all this information back to Google Analytics and getting accurate information as to what step the user is on is not working well.
Sounds like you're looking for:
GFFormDisplay::get_current_page( $form_id );
For the JS approach use:
<script type="text/javascript">
jQuery(document).on('gform_post_render', function(event, form_id, current_page){
// code to trigger on form or form page render
});
</script>
https://docs.gravityforms.com/gform_post_render/

Change Wordpress feed <link> for one specific tag

I have an external page that reads a RSS feed for a tag. I can't change anything on the external page, so the challenge is to change the RSS feed on my side to match the requirements.
On the external page the 3 latest posts for a tag are shown, and at the end of the section (note: not after each post but after all 3 posts) there is a "View all" link. This link receives its value from the element in the feed, which is by default set to my blog homepage, e.g. http://myblog.com). For this specific tag the link should be http://myblog.com/tag/myspecialtag.
The requirement is that the "View all" link links to the tag page instead of the homepage.
My idea was to add a condition to the element to change the URL for this specific category. I tried to change the feed template as recommended here: Customizing feeds, but for some reason it doesn't change the template at all. The code I tried is the following:
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'change_feed_rss2', 10, 1 );
function change_feed_rss2( $for_comments ) {
$rss_template = get_template_directory() . '/feeds/feed-custom_rss2.php';
if( file_exists( $rss_template ) )
load_template( $rss_template );
else
do_feed_rss2( $for_comments ); // Call default function
}
Of course I created the custom feed template and stored it in the feeds directory in my theme.
As this didn't work I tried looking into filters/hooks but I couldn't find anything helpful regarding my issue. Any ideas on how to best solve this issue?
I came up with the following solution:
I created a new custom page template custom_rss-feed.php and copied the code from wp-includes/feed-rss.php into it. I assigned this template to a new page. Additionally I added a filter to get_bloginfo_rss like the following:
function alter_bloginfo_rss($value, $key) {
if ( $key === "url" &&
is_page_template("custom_rss-feed.php")
) {
return $value . "/my/custom/url";
}
return $value;
}
add_filter("get_bloginfo_rss", "alter_bloginfo_rss", 10, 2);

WooCommerce Registration Shortcode - Error messages problems

I am currently creating a widget to display the registration form on a WordPress website that uses WooCommerce. For now, I only have 3 basic fields which are email, password, repeat password. I'm looking forward to add more WooCommerce fields, but want to solve that problem before jumping to the next step.
I'm having some problems with the messages output (wrong password, account already exists, etc).
I searched on the web and there was no shortcode already built for WooCommerce registration, beside their registration page. So I went ahead and created a shortcode, with a template part.
function custom_register_shortcode( $atts, $content ){
global $woocommerce;
$form = load_template_part('framework/views/register-form');
return $form;
}
add_shortcode( 'register', 'custom_register_shortcode' );
This is a snippet I use to get the template part inside a variable, since the default function would "echo" the content instead of "returning" it.
function load_template_part($template_name, $part_name=null) {
ob_start();
get_template_part($template_name, $part_name);
$var = ob_get_contents();
ob_end_clean();
return $var;
}
So, the problem is, when I call woocommerce_show_messages or $woocommerce->show_messages(); from my template part, nothing is showing, or if it is, it shows at the top of the page.
I did try to put the calls inside my shortcode function:
function custom_register_shortcode( $atts, $content ){
global $woocommerce;
$woocommerce->show_messages();
$form = load_template_part('framework/views/register-form');
return $form;
}
add_shortcode( 'register', 'custom_register_shortcode' );
Doing so, the message output inside the <head> tag, which is not what I want.
I tried to do the same trick with ob_start(), ob_get_contents() and ob_clean() but nothing would show. The variable would be empty.
I also did try to hook the woocommerce_show_messages to an action as saw in the core:
add_action( 'woocommerce_before_shop_loop', 'woocommerce_show_messages', 10 );
For something like:
add_action( 'before_registration_form', 'woocommerce_show_messages');
And I added this in my template-part:
<?php do_action('before_registration_form'); ?>
But I still can't manage to get the error messages show inside the box. It would always be inserted in the <head>
I will share final solution when everything is done.
Thanks for your time,
Julien
I finally got this working by hooking a custom function to an action which is called in my header.php
I guess hooking functions inside template part does not work as intended.
In header.php, I got this:
do_action('theme_after_header');
And here's the hooked function. Works perfectly.
function theme_show_messages(){
woocommerce_show_messages();
}
add_action('theme_after_header', 'theme_show_messages');
However, I will look into 'unhooking' the original show message function since it might show twice. Need to test some more ;)
You can also just use the [woocommerce_messages] shortcode in your template where you want it displayed
Replying to a bit of an old question, but you can also try the following:
$message = apply_filters( 'woocommerce_my_account_message', '' );
if ( ! empty( $message ) ) {
wc_add_notice( $message );
}

Resources