【问题标题】:How to get image caption text when calling all images attached as an array [duplicate]调用作为数组附加的所有图像时如何获取图像标题文本[重复]
【发布时间】:2015-06-19 10:22:18
【问题描述】:

我正在尝试获取存储在 WordPress 图像标题中的文本。我有代码可以将图像附加到帖子中,并且我可以稍后在页面中显示它们。

这就是将图片附加到帖子的原因。

<?php
              if ($attachments = get_children(array(
                  'post_type' => 'attachment',
                  'post_mime_type' => 'image',
                  'numberposts' => -1,
                  'post_status' => null,
                  'post_parent' => $post->ID
                      )));

              foreach ($attachments as $attachment) {

                  $mynewarray = wp_get_attachment_image_src($attachment->ID, 'full');
                  $anotherarray [] = $mynewarray[0];
              } ?>

这会显示每个图像,我只是将 [2] 更改为调用不同的图像。

<?php echo $anotherarray[2]; ?>

一切正常,但我想将文本存储在标题中,几个月前我开始这样做,花了几天时间试图获得标题,现在放弃了,现在才回来。如此迷失,感谢任何帮助。

感谢您的建议,但还没有任何效果,我认为这是因为我将附加到帖子的所有图像称为数组。然后使用数组部分将图像设置为div的背景。帖子中列为微笑问题的方法在这种情况下不起作用。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    每个附件在posts 表中都有自己的行。该行的post_excerpt 列包含标题。

    因此,假设您知道附件的 ID,这将获得附件的标题。

    $attachment = get_post( $attachment_id );
    $caption = $attachment->post_excerpt;
    

    阅读本文了解更多详情,尤其是来自 post_meta 的 ALT 标签。

    https://wordpress.org/ideas/topic/functions-to-get-an-attachments-caption-title-alt-description

    编辑

    您的代码中似乎有一个循环。你不能像这样抓住每个附件的 post_excerpt 吗?除非出现严重错误,否则这应该可以工作。

    foreach ( $attachments as $attachment ) {
       $att = get_post( $attachment->ID );
       $caption = $att->post_excerpt;
       /*... */
       $mynewarray = wp_get_attachment_image_src($attachment->ID, 'full');
       $anotherarray [] = $mynewarray[0];
    } 
    

    你也可以试试get_post_field。那个很好,因为它会压缩字段的内容,所以它适合 html 显示。

    foreach ( $attachments as $attachment ) {
        $caption = get_post_field( 'post_excerpt', $attachment->ID );
         /* ... */
    }
    

    【讨论】:

    • 感谢您的帮助 Ollie,这没有用,或者我应该说我还没有让它工作。我正在使用代码的第一部分将附加到帖子的所有图像作为数组调用,然后使用代码的第二部分设置 div 的背景图像(在本例中为 3 个 div)。我想显示div里面的标题文本。
    • 感谢 Ollie,我正在慢慢了解您的进展情况。我已经尝试了你的建议,但还没有得到它(100% 我的错我说)。你能用你的方法告诉我,然后我将如何显示标题,就像我回显 $anotherarray[0] 给我图像网址一样。这个方法会返回一个标题数组吗?
    【解决方案2】:

    看看这个函数wp_prepare_attachment_for_js($attachment_id) - link

    它将返回这些字段:

    id
    title
    filename
    url
    link
    alt
    author
    description
    caption
    name
    status
    uploadedTo
    date
    modified
    menuOrder
    mime
    type
    subtype
    icon
    dateFormatted
    nonces
    editLink
    sizes
    width
    height
    fileLength
    compat
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2014-05-08
      • 2013-12-23
      • 2017-11-12
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多