2

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.

1 Answer 1

2

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

5
  • 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
    Commented Oct 17, 2012 at 7:52
  • Oh, you should use single quotes around the JSON encoded data. I’ll fix the example.
    – fuxia
    Commented Oct 17, 2012 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
    Commented Oct 24, 2012 at 1:16
  • @kyle See my update.
    – fuxia
    Commented Oct 24, 2012 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
    Commented Nov 3, 2012 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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