Skip to content
Open
4 changes: 2 additions & 2 deletions php/class-ad-layers-post-type.php
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ public function save_post( $post_id, $post, $update ) {

$ad_layers[ $position ] = $new_layer;

update_option( 'ad_layers', apply_filters( 'ad_layers_save_post', $ad_layers ) );
update_option( 'ad_layers', apply_filters( 'ad_layers_save_post', array_values( $ad_layers ) ) );
}

/**
Expand All @@ -369,7 +369,7 @@ public function delete_post( $post_id ) {
}
}

update_option( 'ad_layers', apply_filters( 'ad_layers_delete_post', $ad_layers ) );
update_option( 'ad_layers', apply_filters( 'ad_layers_delete_post', array_values( $ad_layers ) ) );
}

/**
Expand Down
23 changes: 23 additions & 0 deletions php/class-ad-layers.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public function setup() {

// Set the active ad layer before anything else.
add_action( 'wp_head', array( $this, 'set_active_ad_layer' ), 1 );

// Check for Ad Layer Post orphans before ad_layers option gets saved
add_filter( 'pre_update_option_ad_layers', array( $this, 'maybe_remove_ad_layer_orphans' ), 10, 2 );
}

/**
Expand Down Expand Up @@ -420,6 +423,26 @@ public function get_current_page_type() {

return apply_filters( 'ad_layers_current_page_type', $page_type );
}

/**
* Finds and removes orphaned Ad Layers prior to the ad_layers WP option
* being updated in the database.
*
* @access public
* @param array $ad_layers
* @return array
*/
public function maybe_remove_ad_layer_orphans( $value, $old_value ) {
$ad_layers = array();

foreach ( $value as $ad_layer ) {
if ( null !== get_post( $ad_layer['post_id'] ) ) {
$ad_layers[] = $ad_layer;
}
}

return count( $value ) === count( $ad_layers ) ? $value : $ad_layers;
}
}

Ad_Layers::instance();
Expand Down