• Hi,

    I have a custom posts set up to run a catalogue. Many of the items in the catalogue have exactly the same title.

    Im using the code below to output all the page titles as a list that you can click on as a search.

    So I’m using the title (not linking to a post) to create a search query in effect. As there are multiple titles i want to remove duplicates in the list, is this possible?

    For example currently titles you would see:

    Cats
    Cats
    Cats
    Dogs

    But i need:

    Cats
    Dogs

    <?php
    $lastposts = get_posts('&post_type=catalogue&orderby=title&order=ASC&numberposts=-1');
    foreach($lastposts as $post) :
    setup_postdata($post);
    // somehow remove duplicates titles?
    ?>
    
    <li>
    <a href="?s=<?php the_title(); ?>&post_type=catalogue">
    <?php the_title(); ?>
    </a>
    </li>
    
    <?php endforeach; ?>
Viewing 1 replies (of 1 total)
  • Thread Starter bradical911

    (@bradical911)

    A friend offered this solution which works nicely. However he points out that:

    The problem with that is there will be a load of unnecessary looping. Say you get 1000 rows back from the database but it only actually outputs 2.

    For me it works fine on a small site but would be interested in anything that can reduce querys to the DB.

    <ul>
            <?php
              /**
               * Create an array to hold all of the post titles
               */
              $post_titles = array();
    
              $lastposts = get_posts('&post_type=catalogue&orderby=title&order=ASC&numberposts=-1');
    
              foreach($lastposts as $post) :
    
                $post_title = get_the_title();
    
                if(!in_array($post_title, $post_titles)) :
    
                  /**
                   * Add the post title to the array
                   */
                   array_push($post_titles, $post_title);
                   setup_postdata($post);
                   // somehow remove duplicates titles?
            ?>
              <li>
                <a href="?s=<?php the_title(); ?>&post_type=catalogue">
                  <?php the_title(); ?>
                </a>
              </li>
            <?php
                endif;
              endforeach;
            ?>
            </ul>
Viewing 1 replies (of 1 total)
  • The topic ‘Get posts – remove duplicate titles from loop’ is closed to new replies.