Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm new to wordpress and trying to make a theme. I'm using a jQuery filter script on a page of posts that filters the posts nested in an unordered list using the HTML data-attribute as a hook in the list items.

I want to use each post's tags as the data attribute hook. I've looked up variations of the_tags() functions, but I can't seem to create one that will simply list the tags as separated by commas without the extra anchor tags, etc.

This is the closest I can get to what I want:

<li class="griditemleft" data-="<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $sep . $tag->name; $sep = ', ';
}
}
?>">

It looks right in the first list item, but the subsequent list items have an extra comma at the beginning of the data attribute string.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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).

console output

Now you can iterate over that array and do something awesome. :)

share|improve this answer
    
Thanks very much for answering this. I've been able to incorporate the json_encode on the page, but I can't seem to wrap my head around the jQuery parseJSON. This is what the "data-tag" looks like without parseJSON working: `<li class="threecol" data-="["branding","logo"]"> May you give me an example of how to iterate over the li items in JavaScript? –  kyle Oct 17 '12 at 7:52
    
Oh, you should use single quotes around the JSON encoded data. I’ll fix the example. –  toscho Oct 17 '12 at 8:53
    
Hey @toscho, any luck fixing the example? I haven't figured out how get it all to work yet. Thanks again for any help you can give. –  kyle Oct 24 '12 at 1:16
    
@kyle See my update. –  toscho Oct 24 '12 at 9:20
    
Hey @toscho Thanks for taking the time to reply. I worked with the code you gave me and the array was still outputting ["tag1", "tag2", "tag3"]. So, when calling the $tag_data inside sprintf() I used str_replace() to remove the unnecessary characters and add necessary blank spaces after the commas like so: str_replace(',', ', ', str_replace(array('[',']','"'),'', $tag_data)) Still, I'm not sure I would have figured it out without your initial help. Thanks again! Can I buy you a beer? –  kyle Nov 3 '12 at 10:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.