Support » Fixing WordPress » Use post_name as ID for list

  • I’m using a custom query to pull certain pages that match a certain category, and to return this as an unordered list. Everything works great, but I can’t access the post_name field. The ‘loop’ is using this: setup_postdata($post); to set up the info so I can use functions like the_ID() and the_title() to use things how I want (I know that a list_pages function exists, but this custom one I made is a little more flexible).

    Why can I not get to the post_name field? My query is selecting everything (“SELECT wp_posts.* FROM…”) I don’t see where there is a post_name() function, so I tried to make my own, just duplicating the_ID() and changing the right things, but it doesn’t return anything.

    Short of making a function, I assume there must be some other way to get to the data. Following is a short version of what I’m doing, without all my extra custom markup:

    $pageposts = $wpdb->get_results("SELECT wp_posts.* FROM $wpdb->posts wp_posts, $wpdb->postmeta wp_postmeta
    WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'mykey' AND
    wp_posts.post_status = 'publish' ORDER BY wp_postmeta.meta_value ASC", OBJECT);
    <?php if ($pageposts): ?>
    <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>

    I really need to know how to do something like this:

    <li id="<?php the_post_name(); ?>">item 1</li>
    or even
    <li id="<?php echo $post_name; ?>">item 1</li>

    so I can manipulate the line items with CSS.

    I’ve been googling this like crazy. I know I can just make a new custom field and call it with a custom field plugin, but I’d rather not go through the extra step, because post_name is already sitting there, waiting to be used! Thanks.

Viewing 1 replies (of 1 total)
  • Sure enough, you post something and then figure it out 5 minutes later. I found a function called permalink_anchor and duplicated that, then modified the new function into just what I needed. Here’s the new function:
    function post_name() {
    global $post;
    $title = sanitize_title($post->post_title);
    echo $title;

    Now I can just go:
    <li id="<?php post_name(); ?>">My Line Item</li>
    and I get
    <li id="my-line-item">My Line Item</li>
    which was all I was looking to do. Hope that helps someone else out.

Viewing 1 replies (of 1 total)
  • The topic ‘Use post_name as ID for list’ is closed to new replies.