Rewrite a link in a button in wordpress using wp_head hook and jquery

You are reading this article because you have a WordPress page with a button and when a certain page loads, you want to rewrite the link on the button.

The code below can be used as a plugin or as a standalone function in your theme functions.php.

We made this for a client who needed to rewrite a booking button in their main navigation so when certain pages were loaded, it would revert to a anchor link to a form on the page, otherwise it would link to a contact page. 

In the code you will see an array of page id's defined in $array_of_groups_ids, so just add your page id's to that array and when the page is loaded it will rewrite the link within the div on the page. 

/* 
Plugin Name: Hotfix 1 - Rewrite Booking Button Link
Version: 1.0
Author: Craig Edmonds from JUCRA Digital
Email: craig@jucra.com
Description: Created on 1st of July 2020. This plugin will detect the groups page in any of the languages and rewrite the BOOK HERE button in the header menu to point to #booking-form on the same page. The plugin uses jquery to swicth out the url. The groups page id is: 1551.
Author: jucra.com
Author URI: https://www.jucra.com
*/

add_action('wp_head', 'jucra_booking_link', 10);
function jucra_booking_link() {
    
    //define list of page id's to look out for
    $array_of_groups_ids = array(1551, 2096);

    //if the page is in the array, display the jquery function
    if(in_array(get_the_ID(), $array_of_groups_ids)) {
        
        echo PHP_EOL . PHP_EOL;
        echo '<!--JUCRA SPECIAL HOOK FOR BOOKING BUTTON -->' . PHP_EOL;
        echo '<!--added on 1/7/2020 by craig@jucra.com -->'. PHP_EOL;
        echo '
        <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery(".et_pb_menu_page_id-246 a").attr("href","#booking-form");
            jQuery(".et_pb_menu_page_id-2188 a").attr("href","#booking-form");
        });
        </script>
        ';
        echo PHP_EOL . PHP_EOL;
        echo '<!--end of hotfix -->'. PHP_EOL;
        echo PHP_EOL . PHP_EOL;
    }

}




  • jquery
  • 2 Users Found This Useful
Was this answer helpful?

Related Articles

customised wordpress wp-config file

Out of the box, the WordPress wp-config.php file is basic and ugly.Below is our standard...

Fix WordPress 404 Errors on Password Protected Directories

You are reading this article becasue you have applied password protection on the wp-admin...

Enable Fenced Off Debugging to Your IP in Wordpress

Use the code below to activate the bugging in WordPress but locked down to your IP.Put this in...

How to protect your Wordpress Login from Bots

You are reading this article because you are getting a lot of attacks on your WordPress login...

SVG Logo is not appearing in Wordpress

You are reading this article because you have managed to upload an SVG file to your Wordpress...