0

I like my clients to simply throw their images into the WordPress editor while the script of my custom theme handles everything else. Be it a gallery, a carousel or whatever. So instead of using plugins I usually let them wrap the images into a shortcode. Like this: [images] Image 1, Image 2, ... [/images]

On the code side this means that I have to get rid of the standard WordPress output (which isn't a problem) and to retrieve the IDs of the images instead. Once I retrieved the IDs I can generate any other output easily. This is how I retrieve the desired IDs:

function register_shortcodes() {
  add_shortcode( 'images', 'get_image_data' );
}

function get_image_data( $atts, $image_data_input = null ) {

  /*
  * Find CSS classes generated by WordPress (like 'wp-image-36')
  * and store them into array $image_classes
  */
  preg_match_all( '/wp-image-[0123456789]*/', $image_data_input, $image_classes );

  /* Loop through array $image_classes */
  $n = 0;
  foreach ( $image_classes[0] as $image_class ) {

    /* Crop class names to ID only */
    $image_id = substr( $image_class, 9 );

    /*  Retrieve image metadata by ID, store ID into array $images */
    $images[$n]['id'] = $image_id;

    $n++;
  }

  /*
  * Loop through array $images and generate $image_data_output
  * by adding the desired values
  */
  $image_data_output = '';

  foreach ( $images as $single_image ) {
    $image_data_output .= $single_image['id'] . ', ';
  }

  return ( $image_data_output );
}

So here's my question: My code works fine, but is there a better way to retrieve the IDs only for my shortcode content (instead of all media attached to the post)? I consider searching for CSS classes to crop them into their IDs the very definition of a workaround but I'm unable to find a smarter way.

0

I created a function to retrieve attachment id from it's src, might work in your case scenario as well

function get_attachment_id_from_src ($image_src) {
    global $wpdb;
    $id = $wpdb->get_var('SELECT ID FROM '.$wpdb->posts.' WHERE guid="'.$image_src.'"');    
    return $id; 
}
|improve this answer|||||
  • Hm, maybe it's me but I don't see this working in my case. The input into $image_src would be something messy like <p>[caption id="attachment_36" align="alignnone" width="1024"]<img class="size-large wp-image-36" src="http://... and so on. I could extract the src with preg_match beforehand, but in this case I'd do pretty much the same thing as before: preg_matching myself through HTML code in order to extract lower level information. – Nico Sep 26 '17 at 13:00

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.