TransWikia.com

Randomize attachment IDs

WordPress Development Asked on October 30, 2021

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?

One Answer

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

Answered by Sally CJ on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP