我尝试从当前的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循环有问题吗?
#1
我认为你应该在这一行中使用false而不是true:get_post_meta($ attachment-> ID, ‘_bildnachweis’, true)以获取所有值。 true将仅返回第一个值。 https://developer.wordpress.org/reference/functions/get_post_meta/
#2
我找到了一种可行的方法:
<?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>
评论前必须登录!
注册