Skip to content

Instantly share code, notes, and snippets.

@sardisson
Forked from clreed87/functions.php
Last active May 26, 2018 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sardisson/fa94062ae69c19e74b8f4c08e02c07dd to your computer and use it in GitHub Desktop.
Save sardisson/fa94062ae69c19e74b8f4c08e02c07dd to your computer and use it in GitHub Desktop.
Populate image title, alt-text, caption, and description on upload (only for images uploaded via XML-RPC)
<?php
// Do not include the opening php tag.
// Populate image title, alt-text, caption, and description on upload
// but only if upload is via XML-RPC (thanks Colin Walker)
add_action ('xmlrpc_call', 'check_new_attachment' );
function check_new_attachment( $method ) {
if( 'metaWeblog.newMediaObject' === $method ) {
add_action( 'add_attachment', 'crt_set_image_meta' );
}
}
function crt_set_image_meta( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Set image meta to 'Status: Date'
$timezone = get_option('timezone_string');
date_default_timezone_set( $timezone );
$image_title = 'Status: '.date( 'Y-m-d H.i.s' );
$image_meta = array(
'ID' => $post_ID,
'post_title' => $image_title,
'post_excerpt' => $image_title,
'post_content' => $image_title,
);
// Set the image alt-text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $image_title );
// Set the image meta
wp_update_post( $image_meta );
}
}
@sardisson
Copy link
Author

Updates the original code to only set the $image_meta fields to date/time for images uploaded by XML-RPC, e.g. the metadataless images uploaded by Micro.blog client apps; browser-based uploads will now retain the default WordPress behavior of setting $image_meta fields based on any IPTC metadata in the image.

Props to @colin-walker for finding and introducing me to the "is this happening via XML-RPC?" check and syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment