1
<?php
if(have_posts()){
    while(have_posts()){
        the_post();
        echo get_the_title();
    }
}
?>

this is my loop, really simple, im calling this within a custom page template i made called services, i expect the posts titles to pop up, but instead im just getting services.

4
  • You said it yourself. You're in a page template. If you create a loop in a page template and then echo get_the_post() it's going to give the page title.
    – rudtek
    Jun 2, 2019 at 20:44
  • but it doesnt make sense, why would a get_POST function give me the PAGE and not the post.
    – Eli
    Jun 2, 2019 at 21:13
  • I agree, it's a bit confusing. PAGES are actually just custom posts.
    – rudtek
    Jun 3, 2019 at 14:19
  • get_post() etc work on the global post object when no post is specified in the first parameter. When you're calling have_posts(), the_post(), etc, you're actually asking WordPress to use this global post. In the context of WordPress, Pages, Posts, and Custom Post Types are all "posts", just of different types. So, have_posts() is true because the page you're on is a post, just a post with the post_type of page.
    – phatskat
    Jun 3, 2019 at 16:21

1 Answer 1

2

You are using the default page loop and it will output the current page attributes like title or other. You should create your own loop with custon query instead. See WP_Query or get_posts.

Example

$query = new WP_Query(array(
   'post_type' => 'post',
   'posta_status' => 'publish',
));

if($query->have_posts()){
    while($query->have_posts()){
        $query->the_post();
        echo get_the_title();
    }
    wp_reset_postdata();
}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.