I’d like to have my attachments IDs being random (not sequential). Just like what this plugin does, but for attachments. I’ve tried to look into the source code of the plugin, but it uses filters that are not applicable to attachments.
So, basically this is what the user ID randomization plugin does
if ( ! function_exists( 'dfx_random_user_id_user_register' ) ) {
/**
* Randomizes the user_id for new created users
*
* @param array $data
* @param bool $update
*
* @return array
*/
function dfx_random_user_id_user_register( $data, $update ) {
if ( ! $update ) {
// Locate a yet-unused user_id
do {
$ID = random_int( 1, dfx_random_user_id_get_max_id() );
} while ( get_userdata( $ID ) );
$data += compact( 'ID' );
}
return $data;
}
}
add_filter( 'wp_pre_insert_user_data', 'dfx_random_user_id_user_register', 10, 2 );
Is there a way to do something similar for the attachments IDs?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
For attachment posts, the following should do it, i.e. use the wp_insert_attachment_data hook along with get_post():
function my_random_post_id( $data, $postarr ) {
// Runs if the post is being created and not updated.
if ( empty( $postarr['ID'] ) ) {
// Locate a yet-unused ID in the (wp_)posts table.
do {
// Based on the dfx_random_user_id_get_max_id() function.
$max_post_id = ( ( 9007199254740991 + 1 ) / 2 ) - 1;
$ID = random_int( 1, $max_post_id );
} while ( get_post( $ID ) );
$data += compact( 'ID' );
}
return $data;
}
add_filter( 'wp_insert_attachment_data', 'my_random_post_id', 10, 2 );
// The following is for non attachments.
//add_filter( 'wp_insert_post_data', 'my_random_post_id', 10, 2 );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0