简体   繁体   English

wordpress通过自定义php页面中的帖子循环

[英]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页面中的帖子,但是无论我做什么,都找不到任何帖子,这是我在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. 您应该通过此文件的完整路径要求wp-load.php。

Hardcoded example: 硬编码示例:

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

Softcoded example (suposing your file is in the same directory as WordPress): 软编码示例(假设您的文件与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. 其中一些是WP_Post类的成员变量。 Go to https://codex.wordpress.org/Class_Reference/WP_Post for reference. 转到https://codex.wordpress.org/Class_Reference/WP_Post以供参考。

Here you have a re-writing of your code that displays the titles of the 30 latest posts published: 在这里,您可以重新编写代码,以显示最新发布的30篇文章的标题:

<?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 : wp_count_posts:
@return object Number of posts for each status. @return object每种状态的帖子数。

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. 此外,如果您想查看所有帖子,则the_post不正确。 Look for it at the function reference : https://codex.wordpress.org/Function_Reference/the_post . 在功能参考中查找它: 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! 正如Carlos先生在评论中建议的那样,我将一个参数传递给have_posts方法,现在它可以工作了! 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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