Stop worrying about the potholes in the road and enjoy the journey

Automatically Trash and Delete Polylang Translations When the Main Post Is Removed

Into the file functions.php of the current wp theme add php next code:

add_action('wp_trash_post', function ($post_id) {
    static $in_progress = false;
    if ($in_progress) { return; }
    $in_progress = true;

    if (!function_exists('pll_get_post_language') || !function_exists('pll_get_post_translations')) {
        $in_progress = false;
        return;
    }

    $post_lang = pll_get_post_language($post_id, 'slug');
    $default_lang = function_exists('pll_default_language') ? pll_default_language('slug') : pll_default_language();

    if ($post_lang && $default_lang && $post_lang === $default_lang) {
        $translations = pll_get_post_translations($post_id); // [ lang => post_id ]
        foreach ($translations as $lang => $tid) {
            if ((int)$tid === (int)$post_id) { continue; }

            if (get_post_status($tid) !== 'trash') {
                wp_trash_post($tid);
            }
        }
    }

    $in_progress = false;
}, 10, 1);

add_action('before_delete_post', function ($post_id) {
    static $in_progress = false;
    if ($in_progress) { return; }
    $in_progress = true;

    if (!function_exists('pll_get_post_language') || !function_exists('pll_get_post_translations')) {
        $in_progress = false;
        return;
    }

    $post_lang = pll_get_post_language($post_id, 'slug');
    $default_lang = function_exists('pll_default_language') ? pll_default_language('slug') : pll_default_language();

    if ($post_lang && $default_lang && $post_lang === $default_lang) {
        $translations = pll_get_post_translations($post_id);
        foreach ($translations as $lang => $tid) {
            if ((int)$tid === (int)$post_id) { continue; }

            if (get_post_status($tid) === 'trash') {
                wp_delete_post($tid, true);
            } else {
                wp_trash_post($tid);
                wp_delete_post($tid, true);
            }
        }
    }

    $in_progress = false;
}, 10, 1);

 

0