【问题标题】:Get latest 4 attachments and then link to their post - WP获取最新的 4 个附件,然后链接到他们的帖子 - WP
【发布时间】:2014-06-06 04:58:21
【问题描述】:

我需要一些帮助来修改此代码 (source):

    <?php
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => 4,
        'post_status' => null,
        'post_parent' => any, // any parent
        ); 
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $post) {
            setup_postdata($post);
            the_attachment_link($post->ID, false);
        }
    }
    ?>

现在,它正在从我的 WP 安装中查询所有图像附件,并将最新的 4 个图像附件显示为它们的缩略图版本。我的问题是the_attachment_link 只允许它链接到全尺寸图像或图像的附件页面。我希望它链接到帖子(并且我可以保证每张图片仅附加到 1 个帖子,如果这是一个问题/担忧)。

我尝试过使用其他函数,例如 wp_get_attachment_imagewp_get_attachment_link,但它们最终什么也没有显示(也没有错误)。有什么帮助吗?

【问题讨论】:

    标签: php wordpress image function attachment


    【解决方案1】:

    这是您的解决方案:

    <?php
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => 4,
        'post_status' => null,
        'post_parent' => 'any', // any parent
    );
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $post) {
            setup_postdata($post);
            ?>
            <a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID) ?></a>
        <?php
        }
    }
    ?>
    

    确保 $post->post_parent 有一个值。

    【讨论】:

    • 感谢您的回答!有没有办法让我自动填写$post-&gt;post_parent 位?我在任何循环之外的主页上显示这些图像,所以现在,它们正在链接到主页(如您所料)
    • 如果您从帖子中添加附件/图片,帖子父级将按帖子 ID 自动填充。如果您从媒体库添加附件/图片,则必须手动附加帖子。
    • 如果您的图片是通过帖子添加的,您不必担心帖子的父值:)。我的示例是否不适用于通过帖子添加的图像?
    • 我已经更新了我的代码。固定链接处缺少“回声”。
    • 尝试:get_category_link($childcat-&gt;cat_ID) 而不是 get_permalink($post-&gt;post_parent)
    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多