skip to Main Content

I want to add a class to the download button of all the posts of my wordpress site, but without having to do it in each post

I have umami software running, where I track my traffic, I would like to add events every time someone presses the download button

For that event to be registered, I must add the class "umami–click–download-button" to each button.

I have already tried in many ways but nothing seems to work
the last thing i did was add the following script but it doesn’t work either

<script>
$( "div" ).addClass(function( index, currentClass ) {
  var addedClass;
 
  if ( currentClass === "wp-block-button" ) {
    addedClass = "umami--click--download-button";
  }
 
  return addedClass;
});
</script>   

In the element inspector the button appears as follows

<div class="wp-block-button has-custom-font-size has-large-font-size">
<a class="wp-block-button__link has-white-color 
has-vivid-cyan-blue-to-vivid-purple-gradient-background 
has-text-color has-background wp-element-button" href="https://earnlink.click/" 
style="border-radius:10px" target="_blank"
rel="noreferrer noopener">DOWNLOAD</a></div>

Thank you very much in advance to whoever answers

2

Answers


  1. you need to test the entire class list. see example below. This will add the class to the <div> tag not the <a> tag.

    $("div").addClass(function(index, currentClass) {
      var addedClass;
    
      if (currentClass === "wp-block-button has-custom-font-size has-large-font-size") {
        addedClass = "umami--click--download-button";
      }
    
      return addedClass;
    });
    .umami--click--download-button {
      color: red;
    }
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    
    <div class="wp-block-button has-custom-font-size has-large-font-size">this is a test
      <a class="wp-block-button__link has-white-color 
    has-vivid-cyan-blue-to-vivid-purple-gradient-background 
    has-text-color has-background wp-element-button" href="https://earnlink.click/" style="border-radius:10px" target="_blank" rel="noreferrer noopener">DOWNLOAD</a></div>
    
    
    <div class="wp-block-button has-custom-font-size has-large-font-size">this is a test another test</div>
    
    <div class="wp-block-button ">and another</div>
    Login or Signup to reply.
  2. Here is the correct code. Try this and let me know if it works fine or not. If you see any error in console please provide the error message for debugging

    <script>
        (function ($) {
            $('div.wp-block-button .wp-block-button__link').each(function () {
                const classToAdd = 'umami--click--download-button';
                const button = $(this);
                if (!button.hasClass(classToAdd)) {
                    button.addClass(classToAdd);
                }
            });
        })(jQuery);
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search