Home > Software design >  How to add a class to wordpress buttons
How to add a class to wordpress buttons

Time:09-12

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 >
<a  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

CodePudding user response:

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 >this is a test
  <a  href="https://earnlink.click/" style="border-radius:10px" target="_blank" rel="noreferrer noopener">DOWNLOAD</a></div>

CodePudding user response:

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>
  • Related