Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean orphaned adstxt post types #138

Merged
merged 10 commits into from
Apr 5, 2023
1 change: 1 addition & 0 deletions ads-txt.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,4 @@ function tenup_ads_txt_add_query_vars( $qvars ) {
return $qvars;
}
add_filter( 'query_vars', 'tenup_ads_txt_add_query_vars' );

42 changes: 42 additions & 0 deletions inc/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,9 @@ function settings_screen( $post_id, $strings, $args ) {
update_option( $args['option'], $post_id );
}
}

// Clean orphaned posts
clean_orphaned_posts( $post_id, $args['post_type'] );
?>
<div class="wrap">
<?php if ( ! empty( $errors ) ) : ?>
Expand Down Expand Up @@ -469,3 +472,42 @@ function admin_notices() {
endif;
}
add_action( 'admin_notices', __NAMESPACE__ . '\admin_notices' );

/**
* Clean orphaned posts if found
*
* @param int $option adstxt | app_adstxt post id
* @param string $post_type post type
*
* @return void|boolean
*/
function clean_orphaned_posts( $option, $post_type ) {
if ( ! $option || ! $post_type ) {
return false;
}

sksaju marked this conversation as resolved.
Show resolved Hide resolved
$args = [
'fields' => 'ids', // Only get post IDs
'post_type' => $post_type,
];

$ads_posts = get_posts( $args );

if ( empty( $ads_posts ) ) {
return false;
}

sksaju marked this conversation as resolved.
Show resolved Hide resolved
// Search and remove the element using unset()
$index = array_search( $option, $ads_posts, true );
sksaju marked this conversation as resolved.
Show resolved Hide resolved
if ( false !== $index ) {
unset( $ads_posts[ $index ] );
}

if ( empty( $ads_posts ) ) {
return false;
}

foreach ( $ads_posts as $post_id ) {
wp_delete_post( $post_id, true );
}
sksaju marked this conversation as resolved.
Show resolved Hide resolved
}