WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Need to access post using slug (4 posts)

  1. donnietheg
    Member
    Posted 6 years ago #

    We would like to access a post using only the slug. Can we do this with get_post or is there another way, such as somehow using the slug to get a post ID? If so how can we do this? Thanks a bunch.
    Don

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Code like this will do it.

    <?php
    $my_query = new WP_Query('name=my-post-slug');
    while ($my_query->have_posts()) {
    $my_query->the_post();
    the_title(); // whatever you want to display the post here
    the_content(); // just like a normal Loop
    }
    ?>
  3. donnietheg
    Member
    Posted 6 years ago #

    That works great!

    I am using this to create a specif intro texts for each category and subcategory.

    I give the intro text post for a category or subcategory a slug name composed of the section number followed by "intro", so for category 13 the slug for the intro post would be "13intro"

    (btw, I am editing editing category.php)

    With my additions the code looks like this

    <?php
    $postSlug = $this_category->cat_ID."intro";
    $postSlug = "name=".$postSlug;
    $my_query = new WP_Query($postSlug);
    while ($my_query->have_posts()) {
    $my_query->the_post();
    // the_title(); // whatever you want to display the post here
    the_content(); // just like a normal Loop
    }
    ?>

  4. termserv
    Member
    Posted 5 years ago #

    How can I modify this text to get the post slugs in the loop, to use it in my code?

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags