开发者

Show posts in Category with Tag (Wordpress)

I am trying to display a lists of posts on a custom post template that are in a 'category' and that have a specific 'tag' that matches the title of the post.

For example I have posts by city name,

  • New York
  • Chicago
  • Texas
  • ...etc

I then have several categories,

For every post I make to one of those categories I then assign a post tag that matches the name of the city.

For example if I have a news item for New York, I select the 'News' category and assign the post the 'New York' tag.

When I am on the custom post template page for New York I want to retrieve posts associated with the News category that have the tag name = New York (the title of the post).

However my dilema is that I can not figure out how to dynamically generate the tag name from the title of the post.

Eg.

    <?php 
                            $tag = wp_title('', FALSE);
            query_posts( 'tag=' . $tag . '' );

            if ( have_posts() ) while ( have_posts() ) : the_post();

                    echo '<li>';

                        the_title();

                    echo '</li>';

             endwhile; 

            wp_reset_query(); ?>

But when getting the tag name using wp_title() it would print 'New York' with a space between the words 'New' and 'York'. This doesn't work.

To get it to work it would need to be 'new-york' with the hyphen in place. But I can not figure out how to generate the tag name based on title with hyphens in place of spaces.

I hope this makes sense.

I appreciate any and all efforts in helping.

Thank you.


In the query_posts funciton, the tag parameter refers to the slug, not the name. Unfortunately, the query_posts function cannot accept the tag name; however, there is a wonderful WP function that can act as an intermediary for us. To get the tag information based on the name, you can use this:

$term = get_term_by('name', $name_of_tag, 'post_tag'); 

$term will be an object with the following information:

term_id
name
slug
term_group
term_taxonomy_id
taxonomy
description
parent
count

For instance, you can get the id with $term->term_id. So putting this all together, you should be able to accomplish what you need with:

$tag_name = wp_title('', FALSE);
$term = get_term_by('name', $tag_name, 'post_tag');
query_posts( 'tag_id=' . $term->term_id);

I've not tested what wp_title actually returns, so I don't know if this properly returns the title, but I'm trusting you on this ;)

Sources:

http://codex.wordpress.org/Function_Reference/WP_Query

http://codex.wordpress.org/Function_Reference/get_term_by

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜