从技术上讲,这应该是可行的:
<!--display image-->
<div class="featured-image">
<?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 wp_get_attachment_image( $attachment->ID, \'full\' );
}
}
?>
</div>
<?php
$content = preg_replace(\'/<img[^>]+./\',\'\',get_the_content());
if($content != ""):?>
<!--styled content div-->
<div class="portfolio-content">
<?php echo $content; ?>
</div>
<?php endif;?>
更新时间:
我成功了。但整个想法存在一些缺陷。以下是我所做的:
创建了一个页面向该页面添加1个图像和一些文本然后我添加了上面的脚本。我得到了图像附件,以显示你做了,但没有任何内容。我注意到的第一件事是,为了再次获取页面查询,需要重置查询。因此,在第一个循环之后,您需要插入:
<?php wp_reset_query(); wp_reset_postdata();?>
现在,函数get\\u将正确响应\\u内容。然而,还有两个问题:
preg\\u replace功能删除图像,但不删除图像周围的链接。通常,将图像添加到编辑器时,默认情况下,图像具有链接。因此,当我们检查变量$content是否为空时,它将返回false,因为仍然有一个空的锚定标记留在那里。因此,在这种情况下,您的图像不能有链接。
我还注意到一张图片只能贴在一篇帖子上。这意味着只有在编辑帖子时上传图像时,初始循环才会起作用。您无法使用以前在其他帖子中上载的其他图像。
无论如何,在修复了以上所有问题后,我仍然可以让代码正常工作。
我再次发布代码和更新,并附上评论。看看你能不能让它发挥作用。
<div class="featured-image">
<?php
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => null,
\'post_parent\' => $post->ID
);
//First loop will get all images attached to this post
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_image( $attachment->ID, \'full\' );
}
}
?>
</div>
<?php wp_reset_query(); wp_reset_postdata(); // this will reset the data from the first loop and give us access again to the main post loop?>
<?php
//this will remove the images from the content editor
// it will not remove links from images, so if an image has a link, you will ended up with an empty lin.
$content = preg_replace(\'/<img[^>]+./\',\'\',get_the_content());
//this IF statement checks if $content has any value left after the images were removed
// If so, it will echo the div below it.. if not will won\'t do anything.
if($content != ""):?>
<!--styled content div-->
<div class="portfolio-content">
<?php echo $content; ?>
</div>
<?php endif;?>