@Pista

Как автоматически удалять старые посты, при достижении определенного количество постов?

Нужен сниппет, который будет удалять все посты, при достижении определенного количества постов на сайте. Например, при достижении 100 постов, срабатывает условия -> удаляем все посты.

Необходимо очищать две таблицы wp_postmeta и wp_posts
Нашел в сети такой кусок, но не совсем нужные условия и не работает. Ошибка

Don't Panic
The code snippet you are trying to save produced a fatal error on line 17:

Unclosed '{' on line 2
The previous version of the snippet is unchanged, and the rest of this site should be functioning normally as before.

Please use the back button in your browser to return to the previous page and try to fix the code error. If you prefer, you can close this page and discard the changes you just made. No changes will be made to this site.


add_action( 'publish_post', function ( $post_ID )
{
	$args = [
		'nopaging' => true,
		'fields'   => 'ids'
	];
	$posts_array = get_posts( $args );
	// Make sure that we have post ID's returned
	if ( $posts_array ) {
		// Get all post ids after the 10th post using array_slice
		$delete_posts = array_slice( $posts_array, 1000 );
		// Make sure that we actually have post ID's in the $delete_posts array
		if ( $delete_posts ) {
			foreach ( $delete_posts as $delete_post )
				wp_delete_post( $delete_post, true );
		}
	}
  • Вопрос задан
  • 72 просмотра
Решения вопроса 1
develx
@develx
Web developer
Как то так
add_action(
    'publish_post',
    function() {
        $args = [
            'numberposts' => -1,
            'fields'      => 'ids',
        ];

        $posts = get_posts( $args );

        if ( $posts && count( $posts ) >= 100 ) {
            foreach ( $posts as $post ) {
                wp_delete_post( $post, true );
            }
        }
    }
);
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы