将POST和ECHO结果中的图像总数计算为数字

时间:2016-11-14 作者:Vladislav Bickov

我正在寻找一个功能,将计数和显示。jpg URL或我帖子中的图像,然后回显结果(例如12幅图像)。

我只找到了一种方法来计算帖子中附加的图片。我还找到了一个xpath函数,但我不确定它是否工作,因为我无法让它回显结果。

以下是我目前掌握的情况:

function post_photo_count_xpath( $post_id ) {
global $wpdb;

$post_id_safe = intval( $post_id );

$html = $wpdb->get_row(
    "select * from {$wpdb->posts} where ID={$post_id_safe} limit 1"
);

$doc = new DOMDocument();
@$doc->loadHTML( $html->post_content );
$path = new DOMXpath( $doc );
$images = $path->query( "//img" );

return( $images->length );
}

3 个回复
最合适的回答,由SO网友:jgraup 整理而成

使用regex查找所有URL并按类型筛选。

$post    = get_post( 504 );
$content = $post->post_content;

// match all urls
preg_match_all( \'/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?/\', $content, $matches );

$count = 0;
if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) {
    foreach ( $matches[ 0 ] as $url ) {
        $split    = explode( \'#\', $url );
        $split    = explode( \'?\', $split[ 0 ] );
        $split    = explode( \'&\', $split[ 0 ] );
        $filename = basename( $split[ 0 ] );
        $file_type = wp_check_filetype( $filename, wp_get_mime_types() );
        if ( ! empty ( $file_type[ \'ext\' ] ) ) {

            // (optional) limit inclusion based on file type
            if( ! in_array( $file_type[ \'ext\' ], array(\'jpg\', \'png\')) ) continue;

            $files[ $url ] = $file_type;
            $urls[]=$url;
            $count ++;
        }
    }
}

// print out urls and total count
print_r( array ( 
        \'total\'  => $count, 
        \'unique\' => array_keys( $files ),
        \'urls\'   => $urls 
) );
如果您想将其作为一个可重用的函数。。。

function get_file_urls( $content = \'\', $file_types = array ( \'jpg\', \'png\' ) ) {

    // match all urls
    preg_match_all( \'/(http:|https:)?\\/\\/([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?/\', $content, $matches );

    $urls  = array ();
    $files = array ();

    if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) {
        foreach ( $matches[ 0 ] as $url ) {
            $split     = explode( \'#\', $url );
            $split     = explode( \'?\', $split[ 0 ] );
            $split     = explode( \'&\', $split[ 0 ] );
            $filename  = basename( $split[ 0 ] );
            $file_type = wp_check_filetype( $filename, wp_get_mime_types() );
            if ( ! empty ( $file_type[ \'ext\' ] ) ) {

                // (optional) limit inclusion based on file type
                if ( ! in_array( $file_type[ \'ext\' ], $file_types ) ) {
                    continue;
                }

                $files[ $url ] = $file_type;
                $urls[]        = $url;
            }
        }
    }

    // print out urls and total count
    return array (
            \'total\'        => count( $urls ),
            \'urls\'         => $urls,
            \'total_unique\' => count( $files ),
            \'unique\'       => array_keys( $files ),
    );
}

$post      = get_post( 504 );
$content   = $post->post_content;
$file_urls = get_file_urls( $content, array ( \'jpg\' ) );
$count     = $file_urls[ \'total\' ];

echo "<div class=\'count\'>${count}</div>";

SO网友:Kanon Chowdhury

有关更多信息,请访问https://blog.josemcastaneda.com/2014/03/18/get-image-count-in-wordpress-post/

// Get all the galleries in the current post
    $galleries = get_post_galleries( get_the_ID(), false );
    // Count all the galleries
    $total_gal = count( $galleries );
    /**
     * count all the images
     * @param array $array The array needed
     * @return int returns the number of images in the post
     */
    function _get_total_images( $array ){
        $key = 0;
        $src = 0;
        while ( $key < count( $array ) ){
            $src += count( $array[$key][\'src\'] );
            $key++;
        }
        return intval( $src );
    }

    echo _get_total_images( $galleries );

SO网友:sMyles

要从HTML内容或PHP字符串/变量中获取所有图像URL,并按特定扩展对其进行过滤,并且仅包括远程域,请使用以下代码:

$data = \'alsdj<img src="http://localdomain.com/donotinclude.jpg">fklasjdf<img src="image.jpg">asdfasdf<img src="http://remotedomain.com/image.jpg">asdfasdfsf<img src="dont_include_me.png">asdfasfasdf\';
$images = array();

// Domains to not include images from (for instances where the full URL is specified to image)
$localhosts = array( \'localdomain.com\' );
// Remove or add any extensions TO be included
$allowed_extensions = array( \'jpg\', \'jpeg\' );

preg_match_all(\'/(img|src)\\=(\\"|\\\')[^\\"\\\'\\>]+/i\', $data, $media);
unset($data);
$data=preg_replace(\'/(img|src)(\\"|\\\'|\\=\\"|\\=\\\')(.*)/i\',"$3",$media[0]);


foreach($data as $url)
{
    $url_data = parse_url( $url );
    $info = pathinfo($url);

    // Goto next, we\'re only looking for remote hosts
    if( ! array_key_exists( \'host\', $url_data ) ) continue;

    // Check if this is an extension we want to include
    if( array_key_exists( \'extension\', $info ) && in_array( $info[\'extension\'], $allowed_extensions) ){

        // Verify this isn\'t one of our local hosts (where the full URL is specified)
        if( ! in_array( $url_data[\'host\'], $localhosts ) ){
            array_push($images, $url);
        }

    }

}

echo \'Total Images: \' . count( $images );
// This is just linebreaks for display formatting
print "\\n\\n";
echo \'Image Data:\';
var_dump( $images );
代码示例:https://glot.io/snippets/ekahzvu8sh

上述代码示例的结果输出:

Total Images: 1

Image Data:array(1) {
  [0]=>
  string(27) "http://remotedomain.com/image.jpg"
}
确保在$localhosts 数组,这样,如果出于某种原因指定了完整的URL,它将不包括该URL。

使用上面的示例代码,下面是更新后的函数,用于使用该代码并返回图像数:

function post_photo_count_xpath( $post_id ) {

    $post = get_post( $post_id );
    if( ! $post ) return 0;

    $data = $post->post_content;
    $images = array();
    // Domains to not include images from (for instances where the full URL is specified to image)
    $localhosts = array( \'localdomain.com\' );
    // Remove or add any extensions TO be included
    $allowed_extensions = array( \'jpg\', \'jpeg\' );

    preg_match_all(\'/(img|src)\\=(\\"|\\\')[^\\"\\\'\\>]+/i\', $data, $media);
    unset($data);
    $data=preg_replace(\'/(img|src)(\\"|\\\'|\\=\\"|\\=\\\')(.*)/i\',"$3",$media[0]);

    if( empty( $data ) ) return 0;

    foreach( $data as $url ){
        $url_data = parse_url( $url );
        $info = pathinfo($url);

        // Goto next, we\'re only looking for remote hosts
        if( ! array_key_exists( \'host\', $url_data ) ) continue;

        // Check if this is an extension we want to include
        if( array_key_exists( \'extension\', $info ) && in_array( $info[\'extension\'], $allowed_extensions) ){

            // Verify this isn\'t one of our local hosts (where the full URL is specified)
            if( ! in_array( $url_data[\'host\'], $localhosts ) ){
                array_push($images, $url);
            }

        }

    }

    return count( $images );
}
资源:https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/