How to get custom variable info from Google Analytics via API - google-analytics

I have data stored in the Second Dimension Google Analytics Events. The field is called Custom Variable (Value 01).
How can I use the GA api to get the values from Custom Variable (Value 01).
I'm using the GA explorer http://ga-dev-tools.appspot.com/explorer/ and can't figure out how to get the Custom Variable.
I see these options:
ga:dimensionXX
ga:customVarNameXX
ga:customVarValueXX
I tried replacing the xx with 01 but I had no luck. Anyone know how I can get the info for GA via API?

Thanks to #Blexy. This was my code at the end:
$params = array(
'metrics' => 'ga:visitors',
'dimensions' => 'ga:customVarValue1,ga:eventLabel,ga:deviceCategory,ga:operatingSystem',
'max-results' => 1000,
'start-date' => $start_date,
'end-date' => $end_date,
);

Try removing the 0.
For example, I have a query like this:
ga:customVarName4=~Previous-Purchases;ga:customVarValue4==1
This gets my custom variable name that matches regex Previous-Purchases AND the custom variable value is equal to 1.

Related

Why does Analytics Data API V1 Beta not conform to the REST spec?

I'm adding GTM and GA4 to some website apps that need to produce detailed stats on the click-throughs of ads per advertiser.
This looks infeasible with standard GA reporting so am using the PHP implementation of Analytics Data API V1 Beta. Since there are few examples (eg analyticsdata/quickstart.php) of V1 reporting using PHP, I am translating other classes and operands from the REST API’s JSON .
<?php
namespace Google\Analytics\Data\V1beta;
require 'vendor/autoload.php';
$property_id = '<redacted>';
putenv('GOOGLE_APPLICATION_CREDENTIALS=Keyfile.json');
$client = new BetaAnalyticsDataClient();
// Make an API call.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '2021-04-01',
'end_date' => 'today',
]
),
],
'dimensions' => [new Dimension(
[
'name' => 'customEvent:link_classes'
]
),
],
'dimensionFilter'=>[new FilterExpression(
[
'filter'=>[new Filter(
[
'field_name' => 'customEvent:Classes',
'string_filter' => [new Filter\StringFilter(
[
'match_type'=> '1',
'value'=> 'AdvertA',
'case_sensitive'=> false
])]])]])],
'metrics' => [new Metric(
[
'name' => 'eventCount',
]
)
]
]);
etc
The Quickstart example works but has endless trouble when a dimensionFilter is added.
For example, match_type should be an enum of one of a few character strings (EXACT, CONTAINS and so on). The JSON definition of match_type only shows the strings (enum 'members') and not any associated values (which would usually be integers). The GA4 migration guide has an example with
"matchType": "BEGINS_WITH"
PHP doesn’t have ‘enum’ but the equivalent would be to select one string and assign it to match_type (vide above). Wrong: StringFilter falls over unless it is given an integer operand, presumably the ordinal number of the desired match in the enum match string (and is the first one 0 or 1?). My understanding of the JSON schema was that an 'enum' list simply restricted the result to one of the unique operands, with an optional check on the operand type. (By comparison, the Python enumerate function returns an object containing a list of pairs with the ordinal number of an operand preceding the operand).
Custom dimensions appear not to conform to the API’s JSON. In Analytics, I specify a custom dimension with a dimension Name of Classes and User Property/Parameter of link_classes**.
However... in the API, dimension Name has to be customEvent:link_classes and not customEvent:Classes. Otherwise it falls over with ‘Field customEvent:Classes is not a valid dimension’
This occurs also when defining field_name in a Filter within a Filter Expression.
So is the API dimension Name not the name of the Analytics dimension Name but actually the Property/Parameter of an Analytics descriptive name? In one place I read the latter: "Custom dimensions are specified in an API report request by the dimension's parameter name and scope." but elsewhere it is implied that Name is the dimension name, e.g. /devguides/reporting/data/v1/advanced:
"dimensions": [{ "name": "customUser:last_level" }]
Finally, even falling in line with what the developers have implemented, dimensionFilter falls over with ‘Expect Google\Analytics\Data\V1beta\Filter\StringFilter’
It is Beta code but one would not expect overt deviations from the REST spec so perhaps I am reading the spec wrongly. Does anyone else have this problem?
** GTM has a ‘Click - Just Links’ trigger where the ‘click URL’ ‘contains’ the advertiser’s URL. The Classes custom dimension in the API dimension Filter has the class values of the adverts click-through links.
To answer the first part of your question, I believe the correct way to use an enum in PHP would be:
'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH
As for the second question. Per the API schema documentation the name of a custom dimension is constructed as customEvent:parameter_name for event scoped dimensions and customUser:parameter_name for user scoped dimensions.
Where parameter_name, as you correctly noted, is not a descriptive name, but rather the event parameter name. In your example you seem to be using a user scoped dimension, so the dimension name in the API should be customUser:link_classes.
Here is a complete example that seems to be running fine:
require 'vendor/autoload.php';
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\FilterExpression;
use Google\Analytics\Data\V1beta\Filter;
use Google\Analytics\Data\V1beta\Metric;
/**
* TODO(developer): Replace this variable with your Google Analytics 4
* property ID before running the sample.
*/
$property_id = 'YOUR-GA4-PROPERTY-ID';
$client = new BetaAnalyticsDataClient();
// Make an API call.
$response = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '2020-03-31',
'end_date' => 'today',
]),
],
'dimensions' => [new Dimension(
[
'name' => 'customUser:link_classes'
]),
],
'dimensionFilter' => new FilterExpression(
[
'filter' => new Filter(
[
'field_name' => 'customUser:link_classes',
'string_filter' => new Filter\StringFilter(
[
'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH,
'value' => 'AdvertA',
'case_sensitive' => false
]
)
])
]),
'metrics' => [new Metric(
[
'name' => 'eventCount',
]
)
]
]);
Many thanks Ilya for a most useful, prompt and correct reply.
Three points:
1.
Using
'match_type' => Filter\StringFilter\MatchType::BEGINS_WITH
instead of:
'match_type' => ‘BEGINS_WITH’
fixes the problem of “Uncaught Exception: Expect integer. in /vendor/google/protobuf/src/Google/Protobuf/Internal/GPBUtil.php” as the
MatchType::BEGINS_WITH (etc) constant returns an integer (in this case 2) from class MatchType.
2.
It would forestall errors if a reminder were added to the places in Custom Dimension documentation where dimension Name is used, such as
/devguides/reporting/data/v1/advanced: "dimensions": [{ "name": "customUser:last_level" }]
emphasising that name is not the dimension Name as defined to Analytics but rather the associated User Property/Parameter name. Or perhaps the Name heading in GA's Custom Dimension 'form' should be amended.
3.
Finally, dimensionFilter falling over with
‘Expect Google\Analytics\Data\V1beta\Filter\StringFilter’
error message was caused by my stupidity in instantiating FilterExpression, Filter and StringFilter as if they were array elements,
e.g
'string_filter' => [new Filter\StringFilter(
rather than
'string_filter' => new Filter\StringFilter(
something that is an unfortunately easy mistake to make when carelessly following the sample report code, where dateRanges, dimensions and so on correctly define arrays (since they can take multiple date ranges and dimensions), e.g.
'dimensions' => [new Dimension (

Woocommerce REST API Retrieve Order By Transaction ID?

I got some problem with Woocommerce REST API.
My goal is simple, to check whether the order is exist or not by transaction ID. So far, parameter that works is order status.
this is my script:
$param = array('status' => 'on-hold', 'transaction_id' => 'XXXXXXXXXXXXXX');
//OR $param = array('search' => 'XXXXXXXX');
$cek = $woocommerce->get('orders', $param);
print_r($cek);
but when I add more parameter like 'transaction_id', the results is weird, resulting all orders.
You can get order data using following way
$order_details = $woocommerce->get('orders/1'); // 1 = Transaction id
I hope it will work for you.

ACF fields value not available until saving post manually

I have some custom post type "video" and I added some custom ACF fields to it ("video_path", "author_name" and "audio_author"). I'm generating posts in that type programmatically like this:
$video_post_params = array(
'post_title' => wp_strip_all_tags($video_title),
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'video'
);
$video_id = wp_insert_post( $video_post_params );
update_field('video_path', $video_path, $video_id);
update_field('author_name', $video_author, $video_id);
update_field('audio_author', $audio_author, $video_id);
All values are inserted well - when I open the post in back-end everything is fine. However, when I try to use those values, I don't get anything?!?
I'm reading values from template files like this:
get_field('video_path', $video_id)
And if I open the post and just save it without any change everything starts working normally and I'm getting post ACF fields normally after that. Posts created manually, from back-end are working well all the time.
What I'm doing wrong? Do I need some extra step when generating posts from code?
The issue is reported here:
http://support.advancedcustomfields.com/forums/topic/programmatic-post-insertion-acf-fields-and-the-save_post-hook/
But that solution is obviously not working for me - my update_field() functions already are immediately after wp_insert_post().
Found it!
When inserting ACF field value field key must be used. If key name is used instead, as I did, everything is inserted well at first look, but value isn't available until post is saved manually. So it's like:
update_field('field_56e683ab6265f', $video_path, $video_id);
update_field('field_56e68415b5c4b', $video_author, $video_id);
update_field('field_56e6842d58740', $audio_author, $video_id);
What a mess....
If you want to use the field name instead of the field key, you can use add_post_meta
For example:
add_post_meta($video_id, 'video_path', $video_path, true);
add_post_meta($video_id, 'author_name', $video_author, true);
add_post_meta($video_id, 'audio_author', $audio_author, true);
With ACF5 you have to use not post id, but post object, lake that:
update_field('field_56e683ab6265f', $video_path, $video);
update_field('field_56e68415b5c4b', $video_author, $video);
update_field('field_56e6842d58740', $audio_author, $video);
I had the same problem, and I correct it with simply add do_action('acf/save_post', $postID); at the end of the script, and that's all…

Prestashop: disable add-to-cart button depending on user group and product

I use Prestashop 1.6.2 and I have a problem trying to add this function.
I am a little bit new trying to mod prestashop, the thing is that I have some products that can be bought only for professionals. Everytime a user registers it's assigned to a user group (professional and no-professional).
I know I can hide the categories for specific user groups, but this method is not perfect, due to if they know the name of the product or search it, they can still access the product page and buy it.
Is there any smarty variable to edit the product.tpl so it displays the button with the conditions above? Or a module or another way to do this?
I don't know exactly is there is a variable already set in smarty or not, but your can define your customer variable with object of customer:
Find controllers/front/ProductController.php file, find method assignPriceAndTax and in the end of it you will find something similar to this:
$this->context->smarty->assign(array(
'quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (float)$tax, $ecotax_tax_amount),
'ecotax_tax_inc' => $ecotax_tax_amount,
'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2),
'ecotaxTax_rate' => $ecotax_rate,
'productPriceWithoutEcoTax' => (float)$product_price_without_eco_tax,
'group_reduction' => $group_reduction,
'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address),
'ecotax' => (!count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((float)$this->product->ecotax) : 0),
'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'),
'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group),
));
Add to this array
'customer_object' => $this->context->customer,
This variable you can use on the product page.
You can use the same way to close those buttons for all 'buy-windows' on your site.

Field api, defining new fields and getting/setting values

I'm able to create a field, using
$form['title'] = array( '#type' => 'text', '#value' => 'Drupal');
1) But I want to be able to get/set the value from the database. How would I do it?
2 )P.S. what's the point of having a '#" in front of type and value ?
First of all I don't know what Drupal version are you using.
Secondly try to get some more info from the my answer:
1) Use Database API in order to get values from database.
2) Read more about Form API.
Hope this helps.

Resources