【问题标题】:Fetch images only from wordpress posts仅从 wordpress 帖子中获取图像
【发布时间】:2013-07-27 05:11:54
【问题描述】:

在wordpress中,当一个帖子类别(或标签)被点击时,所有与点击的类别(或标签)匹配的帖子都会被返回,因为<?php the_content(); ?>

在我的例子中,每个帖子都有一张图片,那么我怎样才能只在点击一个类别(或标签)时获取图片?我不熟悉我需要使用什么代码。

更新:我试图不使用插件。我很抱歉之前没有提到这一点。我想要达到的目标类似于The Sartorialist - 所有帖子都有图片,点击与任何帖子关联的任何类别(或标签),只获取图片。

更新 2:我试过这个:

 <?php   

 $args = array(
   'post_type' => 'attachment',
   'numberposts' => -1,
   'post_status' => null,
   'post_parent' => $post->ID
  );

  $attachments = get_posts( $args );
     if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
           echo '<li>';
           echo wp_get_attachment_image( $attachment->ID, 'full' );
           echo '</li>';
          }
     }

 ?>

唯一奇怪的是,我正试图弄清楚,媒体库中的另一张图片也出现了,但它没有出现在我的任何帖子中。

我还发现this plugin 非常接近我想要的,但不幸的是它必须在单独的页面中,而不是在类别页面中。

【问题讨论】:

    标签: image wordpress post tags categories


    【解决方案1】:

    看看这个plugin这可能就是你要找的东西

    【讨论】:

    • 谢谢@Mark。我没有提到我试图避免使用插件。我查看了插件并阅读了常见问题解答,它看起来不像我正在寻找的东西。我用一个例子更新了我的问题。
    • @phptinkerer 制作插件的人也有它没有here
    【解决方案2】:

    您可以通过以下方式实现此目的:

    <?php
    
    function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
    $imgBeg = strpos($content, '<img', $start);
    $post = substr($content, $imgBeg);
    $imgEnd = strpos($post, '>');
    $postOutput = substr($post, 0, $imgEnd+1);
    $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
    $image[$i] = $postOutput;
    $start=$imgEnd+1;
    }
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
    $more = 0;
    }
    
    ?>
    

    source

    【讨论】:

    • 我试过了,但是当我点击一个类别时没有任何显示。页面完全是空白的。请参阅上面的更新 2。
    • 这是为了获得 1 个帖子。您可能需要对其进行一些更改以运行整个类别
    • 更加专注地完成这个过程。它成功了。同时我发现这和@Mark 一开始指出的一样。谢谢你们。
    • 感谢您挖掘它,但我也必须对 @Mark 公平。已投票。
    • 没问题 - 谢谢。
    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2013-09-21
    相关资源
    最近更新 更多