WordPress Snippets

Check for wordpress plugin updates

<?php
define( 'AFCA_PLUGIN_ID', 836 );

//Plugin Updates
add_filter( 'site_transient_update_plugins', 'afca_viatools_snippets_update_plugin' );
function afca_viatools_snippets_update_plugin( $transient ) {
	require_once ABSPATH . 'wp-admin/includes/plugin.php';

	// Get the path to the main plugin file
	$plugin_dir = plugin_dir_path( __FILE__ );

	// Get the plugin data for the current plugin
	$plugin_data = get_plugin_data( $plugin_dir . 'afca-via-tools-snippets.php' );

	// Retrieve the plugin name
	$plugin_name = $plugin_data['Name'];

	// Retrieve the plugin version
	$plugin_version = $plugin_data['Version'];

	$remote = wp_remote_get(
		'https://andreamorim.test/wp-json/wp/v2/afca-version-control/' . AFCA_PLUGIN_ID,
		[
			'timeout'   => 10,
			'headers'   => [
				'Accept' => 'application/json',
			],
			'sslverify' => false, // disable SSL verification
		]
	);

	if ( is_wp_error( $remote ) || 200 !== wp_remote_retrieve_response_code( $remote ) || empty( wp_remote_retrieve_body( $remote ) ) ) {
		return $transient;
	}

	$remote = json_decode( wp_remote_retrieve_body( $remote ) );

	if ( ! $remote ) {
		return $transient;
	}

	$data = [
		'new_version' => $remote->acf->version,
		'package'     => $remote->acf->url,
	];

	if ( version_compare( $plugin_version, $data['new_version'], '<' ) ) {
		$transient->response[ 'afca-via-tools-snippets/afca-via-tools-snippets.php' ] = $data;
	}

	return $transient;
}

Leave a Reply