1

I'm looking for a function that will count and show .jpg URLs or images in my post and then echo the results (eg. 12 images).

I've only found a way to count the attached images in the post. I also found an xpath function but I'm not sure if it is working, because I can't get it to echo the results.

Here's what I have so far:

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

Use regex to find all the urls and filter by type.

$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 
) );

OOP

If you want this as a reusable function...

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>";
  • It is showing me results as "Array ( [total] => 106 )" but i want to style this print to look it more fancy. Or is it possible to make function from it and put in functions.php and then call it in index.php? – Vladislav Bickov Nov 14 '16 at 2:19
  • Remove the print_r and just echo $count; – jgraup Nov 14 '16 at 2:27
  • Added a function version. – jgraup Nov 14 '16 at 2:40
  • @VladislavBickov Welcome to WPSE. If this answered your question use the check mark on the upper left of the answer to mark it as accepted. Thanks! – Tim Malone Nov 14 '16 at 6:37
0

for more information visit 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 );
  • Some errors in code, i cant echo it in index.php page – Vladislav Bickov Nov 14 '16 at 1:10
  • Please edit your post to include the relevant information here - you can still include the link to credit the author, but links can die over time and we want this site to live on, so making the answer complete is important. Thanks! – Tim Malone Nov 14 '16 at 6:36
0

To get all the image URLs from HTML content, or a PHP string/variable, and filter them by a specific extension, and only include remote domains, use this code:

$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 );

Example of code: https://glot.io/snippets/ekahzvu8sh

Result output of code example above:

Total Images: 1

Image Data:array(1) {
  [0]=>
  string(27) "http://remotedomain.com/image.jpg"
}

Make sure you set what your domain is in the $localhosts array, that way if for some reason the full URL is specified, it won't include that one.

Using the example code from above, here's your updated function to use that code and return the number of images:

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 );
}

Resource: https://davebrooks.wordpress.com/2009/04/22/php-preg_replace-some-useful-regular-expressions/

  • You right im looking to count number of remote urls in posts. Then show results in index. – Vladislav Bickov Nov 14 '16 at 0:55
  • I putted it in my single.php code, but it not counting images, it just shows me that Total images: 2 this info code taking from $data – Vladislav Bickov Nov 14 '16 at 1:10
  • I updated my response and adding an updated version of your function with the example code I provided. – sMyles Nov 14 '16 at 1:20
  • Seems like it is working fine no errors. Now im looking how to show results in my index.php. Ive tried <?php echo count( $images );?> But it showing 0 as results. – Vladislav Bickov Nov 14 '16 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.