Use json_encode()
:
<li class="griditemleft" data-tags="<?php
$posttags = get_the_tags();
$data = array();
foreach($posttags as $tag) {
$data[] = $tag->name;
}
echo json_encode( $data );
Later, in your JavaScript, iterate over the li
items and for each item use:
// get an array of tag names with jQuery's parseJSON()
var itemtags = $.parseJSON( item.data('tags') );
See jQuery parseJSON() for details.
Update
Actually, you don’t even need parseJSON()
in your case, it is much easier with simple tag names. Let’s take a simple function to build a list of the last five posts:
add_action( 'wpse_69446_post_list', 'wpse_69446_post_list' );
function wpse_69446_post_list()
{
$output = '';
$posts = get_posts();
if ( ! $posts )
return;
foreach ( $posts as $post )
{
$tags = get_the_tags( $post->ID );
$tag_names = array ();
$tag_data = '';
if ( $tags )
{
foreach ( $tags as $tag )
{
$tag_names[] = $tag->name;
}
$tag_data = json_encode( $tag_names );
}
$output .= sprintf(
'<li data-tags=\'%1$s\'><a href="%2$s">%3$s</a></li>',
$tag_data,
get_permalink( $post->ID ),
get_the_title( $post->ID )
);
}
print "<ul class='wpse_69446_post_list'>$output</ul>";
// you have to enqueue jQuery first.
// This is just as oversimplified demonstration.
add_action( 'wp_footer', 'wpse_69446_js' );
}
Call it in your theme files with
do_action( 'wpse_69446_post_list' );
Now we need the script for the footer:
function wpse_69446_js()
{
?>
<script>
jQuery( function($) {
$('.wpse_69446_post_list li').each( function( i, item ) {
var li = $(item).find( 'li' );
console.info( 'item li:', li );
// an array or undefined if there are no tags
console.info( 'itemtags:', $(item).data( 'tags' ) );
});
});
</script>
<?php
}
The itemtags
are an array now or undefined
(empty).
Now you can iterate over that array and do something awesome. :)