0

I am trying to remove all stop words from permalinks in Wordpress for future and old content.

Yoast provides this as an option for future URLs but there's no bulk update for old permalinks. I understand generally this would be bad practise to update existing URL's but this is on a development site that has never been live.

I've looked for plugins that do this but haven't been able to find any. There are over a thousand different posts/pages so doing it manually is not an option.

Any ideas?

Thanks

1

This script will do the job:

function wpse_287807_replace_url() {

    // Get all posts
    $query = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => -1,
    ));

    $posts = $query->get_posts();

    foreach ($posts as $post) {

        // Get permalink
        $url = $post->post_name;

        // Stop words array
        $stop_words = array(
            '-a-',
            '-the-',
            '-of-',
        );

        // Replacement
        $replacement = '-';

        // Replace url
        $new_url = str_replace($stop_words, $replacement, $url);

        // Prepare arguments
        $args = array(
            'ID' => $post->ID,
            'post_name' => $new_url,
        );

        // Update post
        wp_update_post( $args );
    }
}

add_action('init', 'wpse_287807_replace_url');

If you have many posts disable creating revision posts by adding WP_POST_REVISIONSconstant to wp-config.php. It will speed up script and reduce the demand for memory usage.

define( 'WP_POST_REVISIONS', false );

| improve this answer | |
  • It's possible that the server will run out of memory if there are "over a thousand.." posts as OP said, the whole result set has to fit in RAM. – Milo Dec 5 '17 at 17:34
  • Interesting observation, for 1000 posts script executes about 30s and use 45mb memory on 1/2 CPU and 512mb machine. – kierzniak Dec 5 '17 at 18:23
  • Thanks @motivast this does exactly what I was after. Is quite heavy on the server so may work out a way to do it in batches – David Gallimore Dec 6 '17 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.