wordpress - get_posts() 对于 post_type 附件总是空的

标签 wordpress

我在处理 Wordpress 主题时遇到以下问题:

如标题所示,尽管帖子肯定包含图片,但 get_posts() 返回的数组经常为空。

我正在使用以下方法来检索附件数组:

$attachments = get_posts( array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'post_parent' => $post_id
) );

现在,$post_id 工作得很好......如果我在上面的代码片段之前回显它,它就会毫无错误地显示出来。我不知道错误在哪里。

为了完整起见,这是整个循环,除了附件检索外,它在各个方面都工作得很好:

           <?php if (have_posts()) : ?>
            <?php while (have_posts()) : ?>
                <?php the_post(); ?>
                <div class="post" id="post-<?php the_ID(); ?>">
                    <div class="post-border">
                        <div class="post-date"><?php edit_post_link('Edit Post', '', ''); ?></div>
                        <?php if($pagename == 'news'): ?>
                            <div class="post-date">Posted: <?php the_time('F j, Y') ?></div>
                        <?php endif; ?>
                        <h5 class="posttitle"><?php the_title(); ?></h5>
                        <div class="post-entry">
                            <?php the_content(); ?>
                            <?php
                                $post_id = $post -> ID;
                                echo $post_id;
                                $attachments = get_posts( array(
                                    'post_type' => 'attachment',
                                    'posts_per_page' => 20,
                                    'post_parent' => $post_id
                                ) );
                                print_r($attachments);
                            ?>
                        <?php echo "<div class='clearboth'></div>"; ?>
                        </div> <!-- end of .entry -->
                    </div> <!-- end of .post-border -->
                </div> <!-- end of .post -->
            <?php endwhile; ?>
        <?php endif; ?>

如果有人有任何建议,我将不胜感激!

最好的, J

最佳答案

附件从父帖子继承 post_status,因此将以下内容添加到 args:

'post_status' => 'inherit',

关于wordpress - get_posts() 对于 post_type 附件总是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549440/

相关文章:

php - 将搜索重定向到主页

php - 根据重量和最小购物车数量免费送货

css - 我需要一些 CSS 来修复我的 wordpress 网站的移动响应能力

WordPress:获取附件,但不获取拇指后的附件

wordpress rest api 响应在 URL 中发送带有正斜杠的 html 内容类型问题

wordpress - 将自定义类添加到 "wp_get_attachment_image( $attachment_id)"wordpress 函数

css - Divi/Wordpress 移动菜单 1click 问题

regex - 使用wp_rewrite规则获取id

javascript - 如果单击指定类别,如何显示/隐藏元数据框

php - 使用 PHP 将一个简单的表单发布到 2 个表