Wordpress:从get_children中排除"插入帖子"的图像

add*_*ely 6 wordpress attachment

我有一个页面顶部有幻灯片,图像内嵌插入内容区域.

我需要从幻灯片中排除已插入帖子的图像.

目前我排除了"特色图片",但这限制了我可以插入帖子的一张图片.

这是我现有的代码:

$thumbnail = get_post_thumbnail_id();
$images = get_children( 'post_type=attachment&post_mime_type=image&order=asc&orderby=menu_order&post_parent='.$post->ID .'&exclude='.$thumbnail);
Run Code Online (Sandbox Code Playgroud)

以前我使用图像元数据的描述字段通过输入'exclude'来排除图像.对于最终用户来说,这并不像我希望的那样好.

任何建议,插件或代码!

更新: 我已经更新了代码,所以现在我从post_content获取任何图像URL并根据幻灯片显示图像进行检查.

    $content = $post->post_content;
    $inlineImages = array();
    preg_match( '/src="([^"]*)"/i', $content, $inlineImages ) ;
    $thumbnail = get_post_thumbnail_id($post->ID);

    $images = get_children( 'post_type=attachment&post_mime_type=image&order=asc&orderby=menu_order&post_parent='.$post->ID .'&exclude='.$thumbnail);

    if ($images) {
        echo '<div id="slideshow">';
        foreach ( $images as $attachment_id => $attachment ) {
            $image = wp_get_attachment_image_src( $attachment_id,array(900,265)); 

            if (!in_array($image[0],$inlineImages)) {
                echo '<img src="'.$image[0].'" width="'. $image[1] .'" height="'. $image[2].'">';
            }
        }
        echo '</div>';
    }
Run Code Online (Sandbox Code Playgroud)

这是一个很好的解决方案,虽然可以改进正则表达式.

一个更好的步骤是将图像数组添加到自定义字段字段,该字段在发布/页面更新或发布时更新.

关于如何解决这个问题的任何建议?

小智 6

只需要做同样的事情.您原来的方法是我想要的方式 - 只是排除插入到帖子中的任何图像出现在滑块中.但我不希望客户做任何特别的事情来实现它.这是我的代码.

$args = array( 'post_type' => 'attachment', 'post_mime_type'=>'image','numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); 
$attachments = get_posts($args);
preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/", $post->post_content, $matches, PREG_PATTERN_ORDER);
/* $matches[1] holds the urls as an array */
foreach ( $attachments as $attachment ) {
if(in_array($attachment->guid, $matches[1])){ continue;}
wp_get_attachment_image( $attachment->ID , 'slider_size'); 
}
Run Code Online (Sandbox Code Playgroud)

第一位获得与帖子相关的所有图像.$ preg_match_all获取帖子正文中的所有图像.然后,当我们遍历图像以在滑块中显示它们时,in_array将检查插入的图像的URL,这些图像的图像的URL将要添加到滑块,如果匹配则跳到下一个图像的URL.

谢谢你发帖,让我思考正确的方向.


add*_*ely 4

我已经更新了代码,所以现在我从 post_content 获取所有图像 URL,并根据幻灯片图像检查它们。

$content = $post->post_content;
$inlineImages = array();
preg_match( '/src="([^"]*)"/i', $content, $inlineImages ) ;
$thumbnail = get_post_thumbnail_id($post->ID);

$images = get_children( 'post_type=attachment&post_mime_type=image&order=asc&orderby=menu_order&post_parent='.$post->ID .'&exclude='.$thumbnail);

if ($images) {
    echo '<div id="slideshow">';
    foreach ( $images as $attachment_id => $attachment ) {
        $image = wp_get_attachment_image_src( $attachment_id,array(900,265)); 

        if (!in_array($image[0],$inlineImages)) {
            echo '<img src="'.$image[0].'" width="'. $image[1] .'" height="'. $image[2].'">';
        }
    }
    echo '</div>';
}
Run Code Online (Sandbox Code Playgroud)