I want to add custom attribute settings to a generated anchor link of WordPress.
This is to let Jquery Mobile find the attributes and makes a button out of it.
Every anchor link, which is generated in WordPress via PHP, contains the page_item class. So my guess is to search for the needed ‘page_item’ class and just add the needed attribute information to generate the needed button.
My header.php file contains the following links to the needed Jquery libraries:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
I wanted to use the following code to add attributes to my anchor links but I just can’t seem to let it work. (This code is placed in the header of the header.php file)
<script type="text/javascript">
$('.page_item').ready(function(){
$(this).attr('data-transition', 'pop');
$(this).attr('data-icon', 'arrow-r');
$(this).attr('data-iconpos', 'left');
$(this).attr('data-role', 'button');
});
</script>
When checking the code via firebug WordPress generates the following code:
<ul>
<li class="page_item page-item-5"><a href="http://localhost/ddwp/?page_id=5">Home</a>
<ul class='children'>
<li class="page_item page-item-11"><a href="http://localhost/ddwp/?page_id=11">Link1</a></li>
</ul>
</li>
<li class="page_item page-item-17"><a href="http://localhost/ddwp/?page_id=17">Link2</a></li>
<li class="page_item page-item-21"><a href="http://localhost/ddwp/?page_id=21">Link3</a></li>
<li class="page_item page-item-23"><a href="http://localhost/ddwp/?page_id=23">Link4</a></li>
<li class="page_item page-item-62 current_page_item"><a href="http://localhost/ddwp/?page_id=62">Link5</a></li>
</ul>
Thanks in advance!
Kind regards
Dragon54
There’s a few reasons your script isn’t working. Here’s some suggestions, and some code that is tested to apply the attributes you are after to the links in the navigation:
ready
away from each separate call to a function that contains all of the calls rather than for each call separately. (I have done that below for you)..page_item
is not a link, it is an li element. Also note that this is ONLY the navigation links – it will not apply to any links in the content of the pages/posts.Jquery in WordPress is not always safe to run using
$
. By wrapping the calls in a document ready called withjQuery
, you can still use$
within the function to call the jQuery functions.EDIT :
Per the excellent comments by @Jasper the much better way to do this would be:
$.ready()
is a special event for document loading, and only works on the document. You need to iterate through the items using$.each()
instead.or just