" prefix to existing conditions and converts legacy data
*
* @since 1.9.1
*/
class Template_Conditions_Upgrader
{
/**
* @var string Version key for tracking upgrade completion
*/
private $upgrade_version_key = 'jltma_conditions_upgrade_v1';
/**
* @var array Mapping of legacy condition values to new format
*/
private $condition_mapping = [
'entire_site' => 'entire_site',
'singular' => 'singular',
'archive' => 'archive',
'search' => 'search',
'404' => '404',
'front_page' => 'front_page',
'post_types' => 'post_types',
'product' => 'product',
'product_archive' => 'product_archive'
];
/**
* Constructor
*/
public function __construct()
{
add_action('admin_init', [$this, 'maybe_run_upgrade']);
add_action('wp_ajax_jltma_force_conditions_upgrade', [$this, 'force_upgrade_ajax']);
}
/**
* Check if upgrade needs to run and execute it
*/
public function maybe_run_upgrade()
{
// Only run in admin
if (!is_admin()) {
return;
}
// Check if upgrade has already been completed
if (get_option($this->upgrade_version_key, false)) {
return;
}
// Check if we have any master_template posts that need upgrading
if ($this->has_templates_to_upgrade()) {
$this->run_upgrade();
}
}
/**
* Check if there are templates that need upgrading
*
* @return bool
*/
private function has_templates_to_upgrade()
{
global $wpdb;
$query = $wpdb->prepare("
SELECT COUNT(p.ID)
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
AND pm.meta_key = 'master_template_conditions_data'
WHERE p.post_type = %s
AND p.post_status = 'publish'
AND pm.meta_value IS NULL
", 'master_template');
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- $query built via $wpdb->prepare() above; direct query required for upgrade check
$count = $wpdb->get_var( $query );
return $count > 0;
}
/**
* Run the upgrade process
*/
public function run_upgrade()
{
global $wpdb;
// Start transaction for data integrity
$wpdb->query( 'START TRANSACTION' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- transaction control; no caching applicable
try {
$upgraded_count = 0;
$templates = $this->get_templates_to_upgrade();
foreach ($templates as $template) {
if ($this->upgrade_template_conditions($template->ID)) {
$upgraded_count++;
}
}
// Commit transaction
$wpdb->query( 'COMMIT' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- transaction control; no caching applicable
// Mark upgrade as completed
update_option($this->upgrade_version_key, true);
// Log upgrade completion
// error_log("JLTMA Conditions Upgrade: Successfully upgraded {$upgraded_count} templates");
// Show admin notice
add_action('admin_notices', function() use ($upgraded_count) {
echo '
';
echo '
Master Addons: Successfully upgraded ' . absint( $upgraded_count ) . ' template conditions to new format.