How to make WordPress Rest API parameters accessible without authentication? - wordpress

How can I make certain parameters of the WordPress Rest API accessible to anyone without first being authenticated – for example, the page parameter doesn't work (where blog is a custom post type) in this query:
mysite.com/wp-json/wp/v2/blog?page=2&per_page=20
I've seen that in the past it's been possible to make these params available, for instance :
add_filter( 'json_query_vars', function( $valid_vars ) {
$valid_vars[] = 'offset';
return $valid_vars;
});
Is there any way to do something similar with today's version of the API?

For anyone who has the same problem, I've solved it. The page parameter is actually publicly available, offset is the one you need authentication for.
The reason the API didn't paginate was because the request url didn't have the paged query string set. Every time I tried to add it with the params option of the WordPress Node API, it didn't work:
wpapi.getNews().params('paged', 'paged').perPage( perPage ).page( pageNumber ).then(data=>
It didn't work because the request url created by the API seemed to always put the page parameter before the paged one, which resulted in paged being ignored when the query actually runs.
So in the end, I created a custom query (bit of a hacked way to do it, but it worked) like so:
Register the route:
wpapi.getNews = wpapi.registerRoute('wp/v2', '/news/(?P<customQuery>)');
Usage:
wpapi.getNews().customQuery('?paged&per_page=20&page='+pageNumber).then(data =>
Using the above, you can build any query, in any order you want. This helped me get the correctly paginated result. Also, we see 'getNews' here because I registered a route for accessing my custom post type called news.

Related

Understand Dynamic Links Firebase

I would like to understand better Firebase Dynamic Links because i am very new to this subject.
What i would like to know :
FirebaseDynamicLinks.instance.getInitialLink() is supposed to return "only" the last dynamic link created with the "initial" url (before it was shorten) ?
Or why FirebaseDynamicLinks.instance.getInitialLink() doesn't take a String url as a parameter ?
FirebaseDynamicLinks.instance.getDynamicLink(String url) doesn't read custom parameters if the url was shorten, so how can we retrieve custom parameters from a shorten link ?
My use case is quite simple, i am trying to share an object through messages in my application, so i want to save the dynamic link in my database and be able to read it to run a query according to specific parameters.
FirebaseDynamicLinks.instance.getInitialLink() returns the link that opened the app and if the app was not opened by a dynamic link, then it will return null.
Future<PendingDynamicLinkData?> getInitialLink()
Attempts to retrieve the dynamic link which launched the app.
This method always returns a Future. That Future completes to null if
there is no pending dynamic link or any call to this method after the
the first attempt.
https://pub.dev/documentation/firebase_dynamic_links/latest/firebase_dynamic_links/FirebaseDynamicLinks/getInitialLink.html
FirebaseDynamicLinks.instance.getInitialLink() does not accept a string url as parameter because it is just meant to return the link that opened the app.
Looks like there's no straightforward answer to getting the query parameters back from a shortened link. Take a look at this discussion to see if any of the workarounds fit your use case.

Google Optimize - create A/B test with dynamic URL

i'm from business and I would like to ask is it possible to create A/B test with dynamic part of URL?
API of backend application returns calculation ID for every visitor and its included on URL.
For example:
We have main URL www.example.pl and I want to create A/B test with redirect to dynamic URL:
www.example.com/calculation/(calculculation_id)
Is it possible?
If your goal is to redirect from https://www.example.com/product/laptop/12345
to https://www.example.com/product/laptop-test/12345 for each product and not for the product 12345.
Select test type redirect
Set up redirect rules for each variant
Customize your page targeting rules with "contains" or "starts with."
Customize your advanced redirection"
1.Set up redirect rules for each variant
Find in domain/path com/product
Replace with com/product-test
Add/modify query parameters/fragments (leave blank)
Original: https://www.example.com/product/laptop/12345
Redirect: https://www.example.com/product-test/laptop/12345 (see point 3.Customize your advanced redirection)
! Do not worry if you are entering the specific product 12345 this value seen by the system as variable xxxxx !
2.Customize your page targeting rules with "contains" or "starts with."
Modify the page targeting rules to ensure that we include any URL containing example.com/product.
3.Customize your advanced redirection.
In our example the text "com/product" is replaced with "com/product-test".
This is the site where you can find more information :
https://support.google.com/optimize/answer/6361119?hl=en
Yes, you can do that in different ways. I'd suggest using Feature Flags approach in your A/B test in order to have a flag to generated the dynamic next URL from the API.
I'll try to summarize in two steps that you should go:
Add a Javascript in the Optimize Visual Editor for. Example here. The idea is this script to add a new flag:
window.FeatureManager = window.FeatureManager || {};
window.FeatureManager.variant_1_to_change_the_url = true;
On your own script, look at this flag to call the backend API in order to get the calculated URL:
// in case of the variant 1
if (window.FeatureManager && window.FeatureManager.variant_1_to_change_the_url) {
// calls the API passing this flag to get the new URL
const redirectURL = fetch('my_endpoint', true/false); // true/false could be the variant verification
location.href = redirectURL; // this is a sample, you can change the URL however you want
} else {
// the original variation
}

Meteor: Single-Document Subscription

Whenever I encounter code snippets on the web, I see something like
Meteor.subscribe('posts', 'bob-smith');
The client can then display all posts of "bob-smith".
The subscription returns several documents.
What I need, in contrast, is a single-document subscription in order to show an article's body field. I would like to filter by (article) id:
Meteor.subscribe('articles', articleId);
But I got suspicious when I searched the web for similar examples: I cannot find even one single-document subscription example.
What is the reason for that? Why does nobody use single-document subscriptions?
Oh but people do!
This is not against any best practice that I know of.
For example, here is a code sample from the github repository of Telescope where you can see a publication for retrieving a single user based on his or her id.
Here is another one for retrieving a single post, and here is the subscription for it.
It is actually sane to subscribe only to the data that you need at a given moment in your app. If you are writing a single post page, you should make a single post publication/subscription for it, such as:
Meteor.publish('singleArticle', function (articleId) {
return Articles.find({_id: articleId});
});
// Then, from an iron-router route for example:
Meteor.subscribe('singleArticle', this.params.articleId);
A common pattern that uses a single document subscription is a parameterized route, ex: /posts/:_id - you'll see these in many iron:router answers here.

How to remove _ga query string from URL

I have a multidomain website for which there is GA tracking. Recently we moved to Universal Analytics and noticed that whenever the domain is changed (from US to Korean/Japanese), a _ga=[random number] is appended to the URL
i.e. from
abc.com
when i click on the japanese site, the URL becomes
japanese.abc.com/?_ga=1.3892897.20937502.9237834
Why does this happen?
How can I remove the _ga part of the URL?
Appreciate your help.
This is needed for cross-domain-tracking (i.e. track people who cross domain boundaries as one visitor and not as one visitor per domain). If you want cross domain tracking you cannot remove this. The _ga - part is the client id which identifies a session and since it cannot be shared via cookies (which are domain specific) it has to be passed via the url when the domain changes.
Since somebody set your site up for cross domain tracking I guess you actually want this (it does not happen by default). The parameter is a necessary side effect of cross domain tracking with Universal Analytics. If you do want this look in the tracking code for any of the linker functions mentioned in the documentation and remove them.
Updated to answer the questions from the comment.
Is there no way to remove the _ga string and still have the cross
domain facility?
No, currently not. Browser vendors work on better ways of cross
domain communication so there might be something in the future, but
at the moment the parameter is the best way.
Also, what if some user randomly changes the _ga value and presses
enter? How will GA record that?
If the user happens to create a client id that has been used before
(highly unlikely) his visit would be attributed to another user.
Realistically Google Analytics will just record him as a new user.
Updated
For those who like to play I did a proof of concept for cross domain tracking without the _ga parameter. Something along those lines could be developed further, as-is it is not suitable for production use.
Update: David Vallejo has a Javascript solution where the _ga parameter is removed via the history API (so while it is still added it is for all intents and purposes invisible to the end user). This is a more elaborate version of Michael Hampton's answer below.
I'm using HTML5 history.replaceState() to hide the GA query string in the browser's address bar.
This requires me to construct a new URL having the _ga= value removed (you can do this in your favorite language) and then simply calling it.
This only alters the URL in the address bar (and in the browser's history). Google Analytics still gets the information passed in via the query string, so your tracking still works.
I do this in a Go html/template:
{{if .URL.RawQuery}}
<script>
window.history.replaceState({}, document.title, '{{.ReplacedURL}}');
</script>
{{end}}
I was asked to remove this tag after it started showing up when we split our website between two domain names. With Apache Rewrite Rules:
RewriteCond %{QUERY_STRING} _ga
RewriteRule ^(.*)$ $1? [R=301,NC,L]
This will remove the tag, but will not be able to pass the _ga params to Google Analytics.
If the user doesn't mind a short refresh, then adding this code to every page
<?php
list($url, $qs) = preg_split('/\?/',$_SERVER['REQUEST_URI']);
if (preg_match('/_ga=/', $qs) ) header( "refresh:1;url=${url}" );
?>
will refresh after a second, removing the query string, but allowing the Google Analytics action to take place. This means that by the time your user has bookmarked or copied your URL, the pesky _ga stuff has long gone.
The above code will throw away ANY query string. This version will just strip out the '_ga' argument.
$urlA = parse_url($_SERVER['REQUEST_URI']);
$qs = $urlA['query'];
if (preg_match('/_ga=/',$qs)) {
$url = $urlA['path'];
$newargs = array();
$QSA = preg_split('/\&/',$qs);
foreach ($QSA as $e) {
list($arg,$val) = preg_split('/\=/',$e);
if ($arg == '_ga') continue; # get rid of this one
$newargs[$arg] = $val;
}
$nqs = http_build_query($newargs);
header( "refresh:1;url=${url}?${nqs}" );
}
You can't stop Google from adding the tag, but you can tell Analytics to ignore it in your reports. Thanks to Russ Henneberry for this: http://blog.crazyegg.com/2013/03/29/remove-url-parameters-from-google-analytics-reports/
It was written before Universal was released, so the language is outdated - now you create a new "view" (rather than "profile"). Creating a new view ensures that you still have the raw data in your default view (just in case you ever need it), so it's really the best solution (keeping in mind that you can't ever apply new settings retroactively in G Ax). Good luck!
You can't remove the _ga parameter from the URL on the website...BUT you can use an Advanced filter in Google Analytics to remove the query parameter from the reports!
Like this:
1) Field A: Request URI
Pattern: ^(.+)\?_ga
2) Field B: not needed
3) Output To -> Constructor
Field: Request URI
Pattern: $A1
This filter that will strip off all query parameters when _ga is the first parameter shown. You can get a lot fancier with the regex, but this approach should work for most websites.
See this page: https://support.google.com/tagmanager/answer/6107124?hl=en
& search for "use hash as delimiter"
Setting this value to true allows you to pass the value through a hash tag instead of through a query parameter
Should fix it
One way to handle this is to use the history.replaceState Javascript function to remove the query string from the URL after the page is finished loading and Google Analytics has done its thing. However, if you remove it too soon, it'll affect GA functionality (one visitor will show as multiple visitors). I've found that the following Javascript (with a 3-second delay)
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, window.location.pathname);}main();"></script>
I used "window.location.pathname" for convenience so that you can use the same script on many pages. However, you can also do like this (for the top page of the site):
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, '/');}main();"></script>
Or for a sub-page:
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, '/something/something.html');}main();"></script>
I did the "data:text/javascript" thing instead of a true in-line script so I could apply "defer" to it, although this probably isn't necessary if you're using a sufficiently long delay value.
You can filter out all (or only include) "?_ga=" parameters in Google Analytics for reporting purposes. I would also highly recommend adding a canonical to the base URL -- or adding the parameters to Google Webmaster Tools -- to avoid duplicate content.

Linkedin Group API call get profile URL of the commented member

I am using Linkedin REST API with PHP.
I am trying to get posts of a particular discussion group.
The API call is
http://api.linkedin.com/v1/groups/2417328/posts:(creation-timestamp,summary,title,type,comments,id,creator:(picture-url,last-name,headline,id,first-name,site-standard-profile-request))?count=100&start=0&modified-since=1312441200000
I would like to fetch the profile URL of the members who commented on each post also. Is it possible to do this with the above mentioned call?
Yes, it is possible - in the API call, specify the comment creator fields you would like to return from the list of available Profile Fields. To return the comment creator's profile URL, replace the comments Group Field with comments:(creator:(site-standard-profile-request)). You can specify other profile fields in there as needed.

Resources