WordPress 6 函数 show_posts 显示每个内容相同的内容

问题描述 投票:0回答:2

它正确循环了 10 次,但内容错误。它使用 id 11 的含量进行合金化

show_posts 有 10 个帖子(这是正确的),但始终是第一个内容

我的

function show_posts
Theme.php
:

    public function show_posts() { # show_posts220914() { 
            $args = array(
            'numberposts'   => 200
        );
        $my_posts = get_posts( $args );
        if( ! empty( $my_posts ) ){
            foreach ( $my_posts as $post ){
                get_template_part( 'content','content');
            }
        }
    }

所以结果是http://localhost/wordpress/

<li>11</li><li>11</li><li>11</li><li>11</li><li>11</li><li>11</li><li>11</li><li>11</li><li>11</li><li>11</li>

show_posts 具有正确的常量,但帖子较少:

在下一次尝试中,我有正确的常量,但帖子较少:

    public function  show_posts(){
        global $wp_query;
        $args = array_merge( $wp_query->query_vars, ['posts_per_page' => 200 ] ); # has no effect here 
        query_posts( $args ); # has no effect here 
        if ( have_posts() ) :
            while ( have_posts() ) : the_post();
                $post= the_post();
                get_template_part( 'content','content');
            endwhile;
        endif;
    }

所以结果是http://localhost/wordpress/

<li>11</li><li>12</li><li>13</li><li>14</li><li></li>

我的

content.php

<li>
    <?php the_title(); ?>
</li>

我的

home.php

<ol>
    <?php 
    do_action( 'home_content' ); 
    ?>
</ol>

我用 http://localhost/wordpress/ 来称呼它。 我不使用任何页面。意味着 http://localhost/wordpress/wp-admin/edit.php?post_type=page 告诉我

No pages found

我在这里找到了灵感:

我使用

WordPress 6.0.2

有什么想法吗?

php wordpress
2个回答
1
投票

您的第二个 WordPress 循环看起来几乎可以工作...我不确定您正在与

$wp_query->query_vars
约束合并的
post_per_page
可以包含什么内容。

尝试这个,更标准的循环(和/或阅读 WordPress Codex 上的循环):

function show_post(){
$args = [
    'posts_per_page' => 10, 
    'post_type' => array( 'post' ),
    'post_status' => array( 'publish' ),
];

$query = new WP_Query( $args );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) :
        $query->the_post();         
 
        get_template_part( 'content','content');   

    endwhile;
endif;

// Restore original Post Data
wp_reset_postdata();
}

0
投票

我得到了正确的输出

<li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li>

如果我用这个:

Theme.php

    public function show_posts_so() { 
        $posts = get_posts(array('numberposts' => -1));
        if ( count($posts)>0 ) :
            foreach($posts as $this_special_post){
                get_template_part( 'content','content', $this_special_post);   
            }
        endif;
    }

content.php

<li><?php echo $args->ID ?></li>

functions.php

add_action( 'home_content', [$theme ,'show_posts_so']);

home.php

    <?php   do_action( 'home_content' );    ?>

它帮助我阅读这篇文章:PHP 中魔术方法 __set_state 的真正目的是什么? 以及有时使用 var_export 命令

© www.soinside.com 2019 - 2024. All rights reserved.