• Hey All,

    I’m trying to get posts by a tag (which, in this case, happens to be the post title). This works fine the when tag is a single word (e.g. ‘tag’), but when spaces (e.g. ‘tag spaced’) are introduced, it doesn’t work properly.

    My solution thus far has been to do the following:

    query_posts( array( 'tag' => str_replace( ' ', '-', get_the_title() ) ) );

    However, I’m not certain this is a viable long-term solution, or even the correct one, at that.

    Can anyone shed some light on this matter?

    Thanks in advance!

Viewing 3 replies - 1 through 3 (of 3 total)
  • You should not use your post title as a tag. Tags are one or two word keywords. There are several ways to query posts by tags, but you need to explain better what you intend to do.

    Thread Starter xcvg

    (@xcvg)

    Thanks for the reply, banago. Let me explain a little further what I’m doing:

    I have a custom post type called ‘Book’. My page-books.php lists all of the Books I have added. A single-book.php shows just the information about that specific book, along with a review of the book.

    My blog, however, talks about general articles related to books and/or authors.

    On my single-book.php, I want to be able to highlight blog posts that have been tagged with the book title. Sometimes, there many not be Books that are tagged at all, which is fine. Sometimes, a Book title may just be one word. Other times, and, more often than the other two scenarios, a Book is tagged, but its title is a multi-word title (herein lies my problem).

    Hopefully this explains more clearly the effect I intend to achieve. Again, if there’s a better way to doing this, I’m open to it.

    OK – now it makes sense. Follow these steps:

    1. Put this code on your functions.php

    // Give me a slug form title
    function sluggify( $url ) {
        # Prep string with some basic normalization
        $url = strtolower($url);
        $url = strip_tags($url);
        $url = stripslashes($url);
        $url = html_entity_decode($url);
        # Remove quotes (can't, etc.)
        $url = str_replace('\'', '', $url);
        # Replace non-alpha numeric with hyphens
        $match = '/[^a-z0-9]+/';
        $replace = '-';
        $url = preg_replace($match, $replace, $url);
        $url = trim($url, '-');
        return $url;
    }

    2. Use this query_post code:

    query_posts( array( 'tag' => sluggify( get_the_title() );

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Retrieve posts by tags with spaces’ is closed to new replies.