Add query string to data-href

I want to add a string after an url inside data-href using jQuery. I want to make sure that my Facebook comments plugin creates a separate thread for each page that loads the comments plugin.

What should be added after the data-href url is ?st=<?php echo $post->post_name;?> – but not sure how to implement this in PHP from WordPress into a jQuery code.

Read More

right now:

<div class="fb-comments" data-href="https://myurl.com" data-width="100%" data-numposts="3" data-colorscheme="light"></div>

what it should look like with post_slug being the slug that WordPress creates for each individual post.

<div class="fb-comments" data-href="https://myurl.com/?st=post_slug" data-width="100%" data-numposts="3" data-colorscheme="light"></div>

Related posts

5 comments

  1. // Select all elements. It seems they are multiple.
    var elems = $('fb-comments'); 
    
    // Get first or you can iterate over above array.
    var elem = elems[0];
    
    // Append whatever text you want.
    //    `$(elem).data('href')` gets current value.
    //    `$(elem).data('href', 'new_val')` sets current value.
    $(elem).data('href', $(elem).data('href') + '?st=<?php echo $post->post_name;?>');
    
  2. If you have jQuery in your page then you can use this script block:

    <script>
        jQuery(function($){
            $('.fb-comments').each(function(){ // loop if there are more blocks
               var oldDataHref = $(this).data('href'); // get the data-href of current "fb-comments"
               var newDataHref = oldDataHref + '?st=<?php echo $post->post_name;?>'; // make a new data-href
               $(this).attr('data-href', newDataHref); // set the data-href here.
            });
        });
    </script>
    
  3. Using jquery:

    var str = "new url";
    
    $(".fb-comments").prop("data-href",str);
    
  4. you need to use json_encode — this returns the JSON representation of a value. You then can manipulate the data-href with the jQuery.

    example below.

    $(document).ready(function() {
          // convert the value
          var value = <?php echo json_encode($post->post_name); ?>
          // get the existing value of data-href
          var href = $('.fb-comments').attr('data-href');
          // create new link with extending php value 
          var newLink = href + '?st=' + value;
          // change the data-href value
          $(".fb-comments").attr('data-href',encodeURIComponent(newLink));
        });
    
  5. Get the link

    var link = document.document.getElementById("fb-comments");
    

    Change the attribute

    link.setAttribute('data-href', "new one");
    

    You can use getAttribute() to get the original and edit it.
    Change the “class” to “id” in your html.

Comments are closed.