Hook WordPress that triggers twice !?

The job of web developer is sometimes complicated!

We sometimes come across very strange bugs on which we spend hours or even days and which can call into question the whole profitability of the project.

My latest is a WordPress hook that was triggered twice. Here is the hook in question:

add_action( 'wp', 'onload' );
function onload()
{
    if ('video' === get_post_type() && is_singular()){
     // Adding an entry in my database
    // ...
    }
}

This code, very simple, had to add a database entry.

It worked very well EXCEPT that from time to time it made TWO records.

After long hours of research, debugging (and depression), I was able to find the origin of the problem:

<link rel='prev' title='My previous video' href='http://localhost/****/video/ma-video-precedente/' />
<link rel='next' title='My next video' href='http://localhost/****/video/ma-video-suivant/' />

WordPress defines by default these two tags to define a link between the contents. The rel=”prev” and rel=”next” tags appeared in 2011 and allow to facilitate the crawl of Google bot on the contents. Some browsers (Chrome, Firefox…) use it to increase the browsing speed between pages by preloading the linked contents.

That’s why my Hook was triggered twice!

How to avoid that the WordPress hook is triggered twice?

Just add this in your functions.php file

remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );

I hope I’ve saved you all the time I lost 🙂

Une question ?

Nos experts se tiennent à votre disposition pour parler de votre projet.

Leave a Reply