我尝试从当前的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.
}
}
?>
【从WordPress中的当前页面获取所有附件】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>
推荐阅读
- 获取所有类别,然后显示每个学期的所有post
- debian安装ncat只为测udp网络通信
- 对象-JavaScript入门基础(016)
- 文件描述符与文件指针的关系与区别
- 计算机入门的一些常用小技巧总结
- shell 脚本一键自动化部署 python3 和 pip3 环境
- 学习Linux tar 命令(最简单也最困难)
- RabbitMQ-进阶
- 详解逃逸分析标量替换栈上分配