Получить все вложения с текущей страницы в Wordpress - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь получить все вложения с текущей страницы WordPress. Но мой код показывает только первый результат. В чем проблема?

Мой код

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

foreach($attachments as $att_id => $attachment) {
  if (get_post_meta( $attachment->ID, '_bildnachweis', true )) {
      $full_img_caption = get_post_meta( $attachment->ID, '_bildnachweis', true );
      echo $full_img_caption; // Here I need more results, but the browser shows me only one.
  }
}
?>

echo $full_img_caption; показывает мне только один результат вместо трех существующих изображений для страницы. Есть проблема с моим foreach l oop?

Ответы [ 2 ]

0 голосов
/ 06 марта 2020

Я нашел способ, который работает:

<?php
//This will return the HTML source of the page as a string.
$htmlString = $post->post_content;

//Create a new DOMDocument object.
$htmlDom = new DOMDocument;

//Load the HTML string into our DOMDocument object.
@$htmlDom->loadHTML($htmlString);

//Extract all img elements / tags from the HTML.
$imageTags = $htmlDom->getElementsByTagName('img');

//Create an array to add extracted images to.
$extractedImages = array();

//Loop through the image tags that DOMDocument found.
foreach($imageTags as $imageTag){

    //Get the alt text of the image.
    $classText = $imageTag->getAttribute('class');


    //Add the image details to our $extractedImages array.
    $extractedImages[] = array(
        'class' => $classText
    );
}

?>
<div id="image-copyright" class="container">
  <strong>Bildnachweis:</strong>

    <?php
    foreach($extractedImages as $image) {
        $unsplittedImage = $image["class"];
        $imageID = explode("wp-image-", $unsplittedImage)[1];

        $full_img_caption = get_post_meta( $imageID, '_bildnachweis', true );
        if ($full_img_caption) {
            echo "<span class='single-author'>". $full_img_caption ."</span>";
        }
        ?>

        <?php
    }
    ?>
</div>
0 голосов
/ 06 марта 2020

Я думаю, вы должны использовать false вместо true в этой строке: get_post_meta( $attachment->ID, '_bildnachweis', true ), чтобы получить все значения. true вернет только первое значение. https://developer.wordpress.org/reference/functions/get_post_meta/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...