简体   繁体   中英

wordpress looping through posts in custom php page

I trying to loop through posts in a custom php page but no matter what I do, no posts are found here is the code I wrote in my-custom-page.php

<?php 
require_once("/wp-load.php");
get_header();?>
<div id="blog">
<?php if(have_posts()) : ?>
 <?php echo"anything"; ?>
<?php endif; ?>
</div>
<?php get_footer();?>

You should require wp-load.php via the full path to this file.

Hardcoded example:

require_once("user/home/public-html/wordpress/wp-load.php");

Softcoded example (suposing your file is in the same directory as WordPress):

require_once(dirname(__FILE__)."/wp-load.php");

You have also to query the posts before you display them. So, you need to add this line to your code:

query_posts('post_type=post');

The query arguments may vary depending on what you want to display. Some of them are the member variables of the WP_Post class. Go to https://codex.wordpress.org/Class_Reference/WP_Post for reference.

Here you have a re-writing of your code that displays the titles of the 30 latest posts published:

<?php
require_once(dirname(__FILE__)."/wp-load.php");
query_posts('post_type=post&showposts=30');
get_header();?>
<div id="blog">
<?php
if (have_posts()) :
   while (have_posts()) :
      the_post();
         the_title();
         echo '<br />';
   endwhile;
else :
    echo 'Sorry, no posts found.';
endif;?>
</div>
<?php get_footer();

wp_count_posts :
@return object Number of posts for each status.

you're trying to echo an object which ends in a fatal error. Furthermore if you want to see all posts the_post is not right. Look for it at the function reference : https://codex.wordpress.org/Function_Reference/the_post . I would do it other (google smth like "get all posts").

as Mr.Carlos suggested through the comments I passed a parameter to the have_posts method and now it works! this code worked for me

`require('./wp-blog-header.php');
 get_header();?>
 <div id="blog">
 <?php if(have_posts(array('post_type' =>'page'))
   {
    echo"anything";
   }?>
 </div>
 <?php get_footer();?>`

如果您将使用主题内的代码,请使用与Carlos先生相同的代码,但不带目录

require_once("/wp-load.php");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM