Adventskalender Day 23 – How to update custom fields in a multi-site

23. December 2013 // by Thomas Scholz // in Adventskalender, Plugins, Tutorial // 1 Comment

marketpress-adventskalender-23
One of the nice things about a multi-site is the possibility to create relationships between posts across the network. For example you might use a private blog in your network to discuss editorial issues and link these conversations to the discussed posts.

Or you create a multi-language network and mark a post on de.example.com as a translation for a post on ru.example.com and en.example.com. You want to provide the post editor for the linked posts, so you can make edits for all of them on one page.

All you need is a simple table for relationships and a routine to update the connected posts, whenever one of them is changed. You will probably use switch_to_blog() and wp_update_post() for that.

It could look like this pseudo-code:

And then you will discover how many plugins are built for single-site installations only and mess up your posts on a multi-site when they are activated network-wide. Why? Because they update the post meta data for all posts without any test to see if they are on the same site as their metaboxes. switch_to_blog() is an unknown factor for most plugins.

The results make users struggle hard: Russian SEO key words are applied to the English site without any notice and no easy way to fix. Strange subtitles appear o the linked posts, or notes meant to stay hidden leak from the editorial blog to the public. And when they change it on the affected posts, all other posts are updated again, this time with new, but still wrong data.

There is a simple fix: pass the source blog’s ID with your data. In your metabox, add a hidden field …

… and in your request validation, before you save any data:

And that’s all. Your users are happy, you will not cause data loss anymore. Even when two plugins use the same field name for this, it will work.


All Adventskalender Posts

About the Author Thomas Scholz

I am a developer and author for MarketPress. In my free time, I am a moderator for several WordPress communities.

1 Trackbacks

  1. toscho on "Multilingual Press Pro and Advanced Custom Fields compatibility" | Wordpress Problems & Erros - How to fix am April 30, 2014

One comment to “Adventskalender Day 23 – How to update custom fields in a multi-site

  1. Eric (@ericandrewlewis)
    December 23, 2013 um 1:47 pm

    Alternatively, you could add the blog ID to the nonce string.

Leave a Reply

Your email address will not be published. Required fields are marked *