Bit of a conundrum today. I implemented some query string into my website so I'd like to retroactively update all my previous (600+) posts to update specific hyperlinks to include this query string.

Example, most of my posts have code like this:

<a data-name="Dish Washer">Dish Washer</a> 

Would it be possible to forcefully update all posts to change the links to this:

<a data-name="Dish Washer" href="/items/?item=Dish Washer">Dish Washer</a>

The hard part is that obviously there is more than just "Dish Washer" and each post contains numerous amounts of items.

I'm trying to figure out if it can possible be done through MySQL but I can't for the life of me figure it out.


This script will get all posts and replace it content according to your needs:

function wpse_287574_replace_content() {

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

    $posts = $query->get_posts();

    foreach ($posts as $post) {

        // Get content
        $content = $post->post_content;

        // Regex and replacement
        $regex = '/^(\<a\s+data-name=\".+\")(\>(.+)\<\/a\>)$/';
        $replacement = '$1 href="/items/?item=$3"$2';

        // Replace content
        $new_content = preg_replace($regex, $replacement, $content);

        // Prepare arguments
        $args = array(
            'ID' => $post->ID,
            'post_content' => $new_content,

        // Update post
        wp_update_post( $args );

add_action('init', 'wpse_287574_replace_content');
  • Thanks for an answer. The issue is though that here is around 9000+ different items than Dishwasher and they all need to be updated. I'm wondering if there is a workaround to do them all at once rather than do 9000+ sql queries. – GenesisBits Dec 3 '17 at 11:50
  • You can do it using php regex I don’t know how looks your data, are this items are similar? Without this information I can’t give answer. – kierzniak Dec 3 '17 at 11:55
  • Basically I have roughly over 9000 different items but they are all in the exact same structure such as <a data-name="Dish Washer">Dish Washer</a>, <a data-name="TV">TV</a>, <a data-name="Microwave">Microwave</a>, <a data-name="Toaster">Toaster</a>, <a data-name="Printer">Printer</a> etc etc. The data-name part is simply referencing my database where all the 9000+ items are stored. – GenesisBits Dec 3 '17 at 13:13
  • I updated my answer. – kierzniak Dec 3 '17 at 13:47

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.