首页 文章

获取最新的4个附件,然后链接到他们的帖子 - WP

提问于
浏览
0

我想要一些修改此代码的帮助(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 ,但它们最终都没有显示任何内容(也没有错误) . 有什么帮助吗?

1 回答

  • 3

    这是你的解决方案:

    <?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 有值 .

相关问题