Version Repository – persist

Please note: Functionality described on this page requires Download Monitor version 4.0 or above.

Versions in Download Monitor can be stored in the database via the Version Repository. persist is a method of Download Monitor’s version repository service. The method stores the given DLM_Download_Version object in the WordPress database. This method can be used for inserting new and updating existing versions. If no ID in the DLM_Download_Version object is set, the version will be inserted as a new version. If an ID is set in the DLM_Download_Version object, the version in the WordPress database with that ID will be updated.

Signature

public function persist( $version ) {}

Parameters

ParameterTypeDefaultDescription
$versionDLM_Download_Versionn/aThe version that will be saved in the WordPress database.

Examples

Inserting a new version

This snippet will create a new DLM_Download object and save it in the WordPress database. In this example, we are creating a new version for a download with ID 11.

// create new version object
$version = new DLM_Download_Version();
$version->set_download_id( 11 );
$version->set_author( 1 );
$version->set_version( "2.1" );
$version->set_date( new DateTime( current_time( 'mysql' ) ) );
$version->set_mirrors( array( "https://150581398.v2.pressablecdn.com/my-file.jpg" ) );

// store the version in the database
download_monitor()->service( 'version_repository' )->persist( $version );

// clear the transient cache. If you don't do this, the version will not be shown.
download_monitor()->service( 'transient_manager' )->clear_versions_transient( 11 );

Please note: We are clearing the version cache which is stored in a transient for download with 11. If you are adding multiple versions, you will only need to call this method once at the very end.

Updating an existing version

This snippet will fetch download with ID 1, change its title, and update it in the WordPress database. The retrieve_single call is wrapped in a try-catch block. You can read here why that is done.


try {
// retrieve version with ID 91
/** @var DLM_Download_Version $version */
$version = download_monitor()->service( 'version_repository' )->retrieve_single( 91 );

// set new version
$version->set_version( "3.0" );

// update version in database
download_monitor()->service( 'version_repository' )->persist( $version );

// clear the transient cache. If you don't do this, the version will not be shown.
download_monitor()->service( 'transient_manager' )->clear_versions_transient( 11 );
} catch ( Exception $exception ) {
// version with ID 91 not found
}
Was this article helpful?
Start Protecting your WordPress Downloads

Protect and track downloads on WordPress... What are you waiting for?