wordpress ajax pagination with history - wordpress

(premise: this is a pretty noob question)
Hi guys,
I am try to code a good ajax navigation/pagination for WordPress.
Currently I am trying to append the new page articles instead of replacing the old ones.
In archive.php I've replaced <?php the_posts_navigation(); ?> with
<nav class="navigation posts-navigation" role="navigation">
<div class="nav-links">
<div class="nav-previous">
<?php next_posts_link(); ?>
</div>
</div>
</nav>
since I want to display only the "Next page" link (which I will style in a button later).
And in my js file I have
$('.nav-previous a').live('click', function(e){
e.preventDefault();
$('.navigation').remove(); // Removing the navigation link at the bottom of the first articles
var link = $(this).attr('href');
$.get( link, function(data) {
var articles = $(data).find('.archive-container');
$('#primary').append(articles);
});
});
It is not that clear to me how to implement history handling in a context like this. I'd like to give users the possibility to scroll up to previous results when clicking on the back button and to keep the results when someone clicks on an article and then goes back to the results.
Now, if I use something like window.history.pushState('', '', link); at the end of the click function above, it changes the URL when pushing the link to see the next articles. And this is correct. But, if I click on an article (e.g. of /page/2) to see it and then I click on the back button, it shows only the results of the page containing that article (that is /page/2 in my example). I'd like to show again all the articles the user saw before leaving the archive page instead.
At the moment I'm also working with window.localStorage to reach the goal, but I'd like to understand if it could be feasible only with history and how to do it.

console.log(window.location.href);
let loc = window.location.href.slice(0, -1);
let ppos = loc.indexOf("page/");
if((ppos >= 0)) {
let page = parseInt(loc.slice(loc.lastIndexOf('/') + 1, loc.length)) + 1;
loc = loc.slice(0, ppos) + 'page/' + page + '/';
} else {
loc += '/page/2/';
}
console.log(loc);
window.history.pushState('', '', loc);

Related

WordPress plugin, display registration page, on button click

I have created a registration plugin in WordPress and I want to display my register-employee.php(under view folder) file. When a user click on a button(used that url to display the file, something like that). Below is my folder structure hope would help.
>controller
>model
>public
>view
register-employee.php
register-member.php
Altough your description is very little,
I give you a really simple guide on how to do this:
First thing, opening a form on click is a javascript thing so the first thing you need to do is add your JavaScript file,
let's assume you have a file assets/js/register.js which looks like this:
var btn = document.querySelector('button.my-register-button');
btn.addEventListener('click', function(e) {
e.preventDefault();
document.querySelector('#my_registration_popup').style.display = 'block';
});
Then we need to add this file to wp_enqueue_scripts action in order to be added to Wordpress pages
add_action('wp_enqueue_scripts', function() {
wp_register_script('my-registration-plugin', YOUR_PLUGIN_URL . '/assets/js/register.js', [], null, true);
});
assuming that your register-employee.php file looks something like this:
<div id="my_registration_popup" style="display: none">
<!-- my form -->
</div>
First thing you need to do is to add above view to wp_footer action:
add_action('wp_footer', function() {
include PATH_TO_YOUR_PLUGIN . '/view/register-employee.php';
});

Add url to a collection links in order to share with other people

Someone knows if there is a plugin for WordPress able to create a collector links in order to share with other people?
I'm searching a solution to create on WordPress an unusual wishlist that not contains products, but links.
In details: i've a list of media products file (brochure pdf, video, data sheets pdf, etc...) and to share with customer a collection of these links I would like to save this links in a "wishli(nk)st". I image that the fastest solution is copy/paste each links...
Thanks everybody!
I'm not aware of any plugins that would implement this without some theme integration. For example, how would the plugin know where to add the wishlink button?
You could use a cookie or html local storage with a little jquery.
Though this example will only be saved in the current user browser.
You could extend this to save the links to logged-in user meta but
would require a little more dev.
Here simple jquery example below using html local storage.
The stackoverflow example below doesn't work because localstorage is blocked on this site in sandbox mode.
See working version here https://jsfiddle.net/joshmoto/yopmbc86/5/
See comments in code...
// add wish link
$('.add-wishlink').on('click', function() {
// get our wish link from current clicked add wish link button
let wishlink = $(this).data('wishlink');
// set our wish link vars
let wishlinks = [];
let duplicate = false;
// if we have wish links
if (localStorage.getItem('wishlinks')) {
// get wish links from local storage and parse data to array
wishlinks = JSON.parse(localStorage.getItem('wishlinks'));
}
// for each of our wish links
$.each(wishlinks, function(index, value) {
// check if link already exists
if (wishlink === value) {
// if link already exists mark as duplicate
duplicate = true;
// show alert to user
alert('Link already added');
}
});
// if wishlink is not a duplicate
if (!duplicate) {
// add new link to wish links array
wishlinks.push(wishlink);
// update the local storge wi
localStorage.setItem('wishlinks', JSON.stringify(wishlinks));
// show alert to user that link has been added
alert('Link added to wishlinks\r\n' + wishlink);
}
});
// share wish links
$('.share-wishlinks').on('click', function() {
// if we have wish links
if (localStorage.getItem('wishlinks')) {
// set our email share vars
let email = '';
let subject = 'My Wishlinks';
let body = 'Here are my Wishlinks...\r\n\r\n';
let wishlinks = JSON.parse(localStorage.getItem('wishlinks'));
// for each of our wish links
$.each(wishlinks, function(index, value) {
// add each link to end of body
body += value + '\r';
});
// open mailto link with wish links
window.open('mailto:' + email + '?subject=' + encodeURI(subject) + '&body=' + encodeURI(body));
} else {
// alert user that they have no wish links
alert('You have no wishlinks.');
}
});
// delete wish links
$('.delete-wishlinks').on('click', function() {
// if we have wish links
if (localStorage.getItem('wishlinks')) {
// remove all wish links from local storage
localStorage.removeItem('wishlinks');
// alert user wish links have been deleted
alert('Wish links deleted.');
} else {
// alert user that they have no wish links
alert('You have no wishlinks.');
}
});
<!-- add buttons into your theme and output the wishlink in the button data-wishlink attribute -->
<button class="add-wishlink" data-wishlink="http://www.example-1.com">
Add link 1 to wish links
</button>
<button class="add-wishlink" data-wishlink="http://www.example-2.com">
Add link 2 to wish links
</button>
<button class="add-wishlink" data-wishlink="http://www.example-3.com">
Add link 3 to wish links
</button>
<br/><br/>
<!-- global button to share wish links as an email -->
<button class="share-wishlinks">
Share wish links
</button>
<br/><br/>
<!-- global button to delete wish links -->
<button class="delete-wishlinks">
Delete wish links
</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Disqus count not refreshing immediately

I registered to Disqus 2 days ago, and I put the script on my website (not a CMS). Basically, it's working, comments are displayed and it's pretty easy.
BUT, the count system is totally screwed up. I get an unique identifier for each post (slug-id):
var disqus_config = function () {
//this.page.url = '/<?= $datas['slug'].'-'.$datas['id']; ?>/'; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = '<?= $datas['slug'].'-'.$datas['id']; ?>'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//my-shortname.disqus.com/embed.js'; // It's the real one, i juste modified it for the post
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
The count.js script is right before the </body> tag
And the code for the count is :
<a href="/<?= $datas['slug'].'-'.$datas['id']; ?>/#disqus_thread"
data-disqus-identifier="<?= $datas['slug'].'-'.$datas['id']; ?>">
</a>
It's working yes, but I need few minutes/hours before refresh. Look at the screenshot, I posted a comment, and the count hasn't been refreshed even if I clear my cache etc. I have to wait some minutes/hours and it'll be refreshed automatically.
Screenshot from my website
Why? How to fix it?

jquery load variable won't load contents

Hi I am using jQuery load to grab a ahref from a link and then I want to load a div from the page im getting into a div so have tried this:
// lets load the contents
$('#navigationLinks a:not(:first-child)').click(function(event){
$('#wrapper').animate({
'left':'0px'
});
var href = $('#navigationLinks a').attr('href');
$('#content').load(href + ' #resultDiv');
event.preventDefault();
});
This is the HTML:
<div id="navigationLinks">
Dashboard Home
Industry Overview
Regions
Industries
Security Pipeline
Audit Events & Issues
Account Filter
Contractual vs. Delivered Services
</div>
I tried removing the space in ' #resultDiv' before the # but that didn't help, any help would be greatly appreciated.
You should try this
$(document).ready(function(){
$('#navigationLinks a:not(:first-child)').click(function(e){
var href = e.target;
$('#content').load(href + ' #resultDiv');
e.preventDefault();
});
});
The problem was that var href = $('#navigationLinks a').attr('href'); will always get the first link in the block and not the actually link that was clicked.

How does google analytics track events when user navigates to other page inside one domain

In Google's documentation it is said that an event can be tracked in the following way:
<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a>
or older version:
<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>
I was looking with Firebug to the request that are made when a click on a link and I see there aborted request:
http://www.google-analytics.com/__utm.gif?utmwv=4.7.2&utmn=907737223&....
This happens because browser unload all javascript when user navigates to a new page. How in this case event tracking is performed?
Edit:
Since one picture can be worth a thousand words...
When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)
The problem is that there isn't enough time for the script to finish running before the user is taken to the next page. What you can do is create a wrapper function for your GA code and in the onclick, call the wrapper function and after the GA code is triggered in your wrapper function, set a time out and update location.href with the link's url. Example:
click me
<script type='text/javascript'>
function wrapper_function(that,category,action,opt_label,opt_value) {
_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
window.setTimeout("window.location.href='" + that.href + "'", 1000);
}
</script>
code will vary a bit based on your link but hopefully you get the idea - basically it waits a little bit before taking the user to the target url to give the script some time to execute.
Update:
This answer was posted several years ago and quite a lot has happened since then, yet I continue to get feedback (and upvotes) occasionally, so I thought I'd update this answer with new info. This answer is still doable but if you are using Universal Analytics then there is a hitCallback function available. The hitCallback function is also available to their traditional _gaq (ga.js) but it's not officially documented.
This problem is answered in Google's documentation:
use
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var myTracker=_gat._getTrackerByName();
_gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
or
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var pageTracker=_gat._getTracker("UA-XXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)
}catch(err){}
}
</script>
This more or less the same as the answer from Crayon Violet, but has a nicer method name and is the official solution recommended by Google.
As above, this is due to the page being unloaded prior to the Async call returning. If you want to implement a small delay to allow gaq to sync, I would suggest the following:
First add a link and add an extra class or data attribute:
My Link
Then add into your Javascript:
$("a[data-track-exit]").on('click', function(e) {
e.preventDefault();
var thatEl = $(this);
thatEl.unbind(e.type, arguments.callee);
_gaq.push( [ "_trackEvent", action, e.type, 'label', 1 ] );
setTimeout(function() {
thatEl.trigger(event);
}, 200);
});
I don't really condone this behavior (e.g. if you are going to another page on your site, try to capture the data on that page), but it is a decent stop-gap. This can be extrapolated not just for click events, but also form submits and anything else that would also cause a page unload. Hope this helps!
I had the same issue. Try this one, it works for me. Looks like that ga doesnt like numbers as a label value. So, convert it to string.
trackEvent: function(category, action, opt_label, opt_value){
if(typeof opt_label === 'undefined') opt_label = '';
if(typeof opt_value === 'undefined') opt_value = 1;
_gaq.push([
'_trackEvent',
String(category),
String(action),
String(opt_label),
opt_value
]);
}

Resources