计算附加到帖子的总图像并在标题中打印结果 - wordpress

问题描述 投票:0回答:2

我想在我的帖子标题中显示图像总数。例如:“我的帖子是这辆车待售(4张图片)”如果这是标题,我想在图片之前的标题中打印4。我尝试了这段代码,但它显示 0。我不知道为什么。那么你能帮我一下吗?请注意:我是 php 和 wordpress 新手。

$count = count( $attachments );
$specific = array();
$i = 1;

foreach ( $attachments as $attachment ) {
    $specific[$attachment->ID] = $i;
    ++$i;
}
php wordpress
2个回答
0
投票

请尝试以下解决方案

为此,您需要传递您的帖子 ID

<?php
$getAttachments = get_children( array( 'post_parent' => $post->ID ) );
$count = count( $getAttachments );
echo $count;
?>

0
投票

第一个解决方案是使用 WP_Query 的高级功能来获取帖子中所有“图像”mime 类型附件的计数。

    $image_IDs = new \WP_Query( array(
            'post_type' => 'attachment',
            'post_mime_type' => 'image',    // Will automatically append subtype wildcard.
            'post_status' => 'inherit',
            'post_parent' => $post->ID,
            'fields' => 'ids',              // Streamline underlying query by only returning IDs.
        ) );
    return( $image_IDs->post_count );

第二个选项是低级的、基于 SQL 的替代方案,如果高级 WP_Query 没有功能:

    global $wpdb;
    return (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT count(*) FROM $wpdb->posts WHERE
                post_type = 'attachment' AND
                post_mime_type like 'image/%' AND
                post_status = 'inherit' AND
                post_parent = %d",
            $post->ID
            )
        );
© www.soinside.com 2019 - 2024. All rights reserved.