【问题标题】:WordPress types plugin getting post's title instead of image's titleWordPress 类型插件获取帖子的标题而不是图像的标题
【发布时间】:2013-03-13 04:32:32
【问题描述】:

我正在使用一个名为 Types 的 wordpress 插件。

我正在使用他们的自定义字段功能将图像上传到我的自定义侧边栏中的画廊。我还使用灯箱来显示这些图像。

所以我正在尝试让每张图片的标题出现

<?php $resortimages = get_post_meta(get_the_ID(), 'wpcf-r-images'); 
foreach ($resortimages as $resortimage) {
echo '<li><a href="'. $resortimage. '" rel="lightbox" title="" ><img src="'. $resortimage. '"/></a></li>';
}

我尝试获取帖子标题,但它只是获取帖子本身的标题。

【问题讨论】:

    标签: php wordpress image custom-post-type


    【解决方案1】:

    Jesper,看起来类型图像字段只存储图像 URL,而不是其内容。如果您想检索一些其他信息(例如标题、标题和描述),您可能必须尝试通过其 URL 获取图像 ID。在你的functions.php中:

    /**
     * Retrieve the attachment ID from its URL
     * 
     * @param string $image_url
     * @return int $attachment[0] The attachment ID
     *
     * @link http://pippinsplugins.com/retrieve-attachment-id-from-image-url/
     */
    function mytheme_get_attachment_id( $image_url ) {
        global $wpdb;
    
        $prefix = $wpdb->prefix;
        $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $image_url ) ); 
            return $attachment[0]; 
    
    }
    

    之后,您可以使用 foreach 并检查您的 ID:

    <?php
    $resortimages = get_post_meta(get_the_ID(), 'wpcf-r-images'); 
    
    foreach ($resortimages as $resortimage) {
    
        // Get attachment ID by its URL
        if ( $resortid = mytheme_get_attachment_id( $resortimage ) )
            $resortname = get_the_title($resortid);
    
        echo '<li><a href="'. $resortimage. '" rel="lightbox" title="' . $resorttitle . ' ><img src="'. $resortimage. '"/></a></li>';
    }
    ?>
    

    但请注意您将执行的查询数量。希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多