WordPress Multisite - catégories globales
-
-
Je suppose quefaire des catégories assignées à une variableglobale,puisimporter sur lethèmeinit.i guess making categories assigned to a global variable and then import on theme init.
- 0
- 2011-03-16
- kaiser
-
Jepense que cette questionest lamême que [Partager unetaxonomie surplusieursblogsen 3.0] (http://wordpress.stackexchange.com/questions/1516/share-one-taxonomy-across-multiple-blogs-in-3-0).Cette questionn'a cependantpas obtenu debonne réponse.C'est une questionintéressante,je vais offrir uneprimepour cela.I think this question is the same as [Share one taxonomy across multiple blogs in 3.0](http://wordpress.stackexchange.com/questions/1516/share-one-taxonomy-across-multiple-blogs-in-3-0). That question did not get a good answer however. It is an interesting question, I'll offer a bounty for it.
- 4
- 2011-05-27
- Jan Fabry
-
4 réponses
- votes
-
- 2011-03-18
function __add_global_categories( $term_id ) { if ( get_current_blog_id() !== BLOG_ID_CURRENT_SITE || ( !$term = get_term( $term_id, 'category' ) ) ) return $term_id; // bail if ( !$term->parent || ( !$parent = get_term( $term->parent, 'category' ) ) ) $parent = null; global $wpdb; $blogs = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}'" ); foreach ( $blogs as $blog ) { $wpdb->set_blog_id( $blog ); if ( $parent && ( $_parent = get_term_by( 'slug', $parent->slug, 'category' ) ) ) $_parent_ID = $_parent->term_id; else $_parent_ID = 0; wp_insert_term( $term->name, 'category', array( 'slug' => $term->slug, 'parent' => $_parent_ID, 'description' => $term->description )); } $wpdb->set_blog_id( BLOG_ID_CURRENT_SITE ); } add_action( 'created_category', '__add_global_categories' );
Celafonctionnera chaquefois qu'une catégorieest ajoutée sur le siteprincipal. Quelquesmisesen garde/points àmentionner;
- Si vous avez beaucoup deblogs,cettefonctionpeut devenir assezintensive.
- Enmoyenne,nousexécutonsentre 5et 8 requêtes (peut-êtreplus) parblog -en fonction de la vitesse de votrebase de données,cettefonction devrapeut-être êtrefragmentée.
- Seules les catégoriesnouvellement ajoutées sont «synchronisées». Lamise àjouret la suppression de catégoriesne le sontpas (le code devra être révisé).
- Si une catégorienouvellement ajoutée a unparentet que leparentestintrouvable dans leblogmultisiteen question,la catégorie sera créée sansparent (celane devrait être le cas que si la catégorieparente a été créée avant que cettefonctionne soitinstallé).
function __add_global_categories( $term_id ) { if ( get_current_blog_id() !== BLOG_ID_CURRENT_SITE || ( !$term = get_term( $term_id, 'category' ) ) ) return $term_id; // bail if ( !$term->parent || ( !$parent = get_term( $term->parent, 'category' ) ) ) $parent = null; global $wpdb; $blogs = $wpdb->get_col( "SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = '{$wpdb->siteid}'" ); foreach ( $blogs as $blog ) { $wpdb->set_blog_id( $blog ); if ( $parent && ( $_parent = get_term_by( 'slug', $parent->slug, 'category' ) ) ) $_parent_ID = $_parent->term_id; else $_parent_ID = 0; wp_insert_term( $term->name, 'category', array( 'slug' => $term->slug, 'parent' => $_parent_ID, 'description' => $term->description )); } $wpdb->set_blog_id( BLOG_ID_CURRENT_SITE ); } add_action( 'created_category', '__add_global_categories' );
This will run whenever a category is added on the main site. A few caveats/points worth mentioning;
- If you have a lot of blogs, this function may get pretty intensive.
- On average, we are running anywhere between 5 to 8 queries (possibly more) per blog - depending on the speed of your database, this function may need to be chunked.
- Only newly added categories are 'synced'. Updating and deleting categories are not (code will need to be revised).
- If a newly added category has a parent, and the parent cannot be found within the multisite blog in question, the category will be created with no parent (this should only be the case if the parent category was created before this function was installed).
-
Y a-t-il - oupourrait-il y avoir - unplugin quifait cela?Avec lesmodificationset les suppressions?Et unepage deparamètrespour choisir quellestaxonomieset à quels sitesenfants l'appliquer?Is there - or could there be - a plugin that does this? Along with edits and deletions? And a settings page to choose which taxonomies and which child sites to apply it to?
- 1
- 2011-04-20
- Marcus Downing
-
Enfait,vous opposeriez-vous sij'utilisais votre code commepoint de départpour écrire unplugin?In fact, would you object if I used your code as the starting point to write a plugin?
- 0
- 2011-04-20
- Marcus Downing
-
Pas deproblème dutout -mes réponsestombent sous la licence de stackexchange,le cc-wiki avec attribution obligatoire :)No problem whatsoever - my answers fall under stack exchange's license, the cc-wiki with attribution required :)
- 0
- 2011-05-05
- TheDeadMedic
-
- 2011-05-30
Oh,laprocrastination du dimanche ...
https://github.com/maugly/Network-Terminator
- Permet d'ajouter destermes demanièregroupée dans réseau
- Vouspouvez sélectionner quels sites seront concerné
- Fonctionne avec destaxonomiespersonnalisées
- Ne supprimepas
- Ne se synchronisepas
C'est quelque chose quej'aifait ces dernières heureset jen'aiplus letemps defaire d'autrestestsmaintenant. Quoi qu'ilen soit - celafonctionnepourmoi! .)
Essayez-le. Il y a aussi unefonctionnalité de «test»implémentée afin que vouspuissiez vérifier le résultat avant defaire quelque chose.
Mise àjour -> Captures d'écran:
Avant l'action:
Après letest:
Leplugin lié ci-dessus ajoute uneinterface utilisateurmais àpeuprèstout ce quiestimportant sepasse dans cettefonction:
<?php function mau_add_network_terms($terms_to_add, $siteids, $testrun = false) { // check if this is multisite install if ( !is_multisite() ) return 'This is not a multisite WordPress installation.'; // very basic input check if ( empty($terms_to_add) || empty($siteids) || !is_array($terms_to_add) || !is_array($siteids) ) return 'Nah, I eat only arrays!'; if ($testrun) $log = '<p><em>No need to get excited. This is just a test run.</em></p>'; else $log = ''; // loop thru blogs foreach ($siteids as $blog_id) : switch_to_blog( absint($blog_id) ); $log .= '<h4>'.get_blog_details( $blog_id )->blogname.':</h4>'; $log .= '<ul id="ntlog">'; // loop thru taxonomies foreach ( $terms_to_add as $taxonomy => $terms ) { // check if taxonomy exists if ( taxonomy_exists($taxonomy) ) { // get taxonomy name $tax_name = get_taxonomy($taxonomy); $tax_name = $tax_name->labels->name; //loop thru terms foreach ( $terms as $term ) { // check if term exists if ( term_exists($term, $taxonomy) ) { $log .= "<li class='notice' ><em>$term already exists in the $tax_name taxonomy - not added!</em></li>"; } else { // if it doesn't exist insert the $term to $taxonomy $term = strip_tags($term); $taxonomy = strip_tags($taxonomy); if (!$testrun) wp_insert_term( $term, $taxonomy ); $log .= "<li><b>$term</b> successfully added to the <b>$tax_name</b> taxonomy</li>"; } } } else { // tell our log that taxonomy doesn't exists $log .= "<li class='notice'><em>The $tax_name taxonomy doesn't exist! Skipping...</em></li>"; } } $log .= '</ul>'; // we're done here restore_current_blog(); endforeach; if ($testrun) $log .= '<p><em>No need to get excited. This was just the test run.</em></p>'; return $log; } ?>
Je reviendraiet modifierai ceci avecplus d'informationsplustard (sinécessaire).
C'est loin d'êtreparfait (lisez lesproblèmes connus dans latête duplugin).
Tout commentaire apprécié!Oh, sunday procrastination...
https://github.com/maugly/Network-Terminator
- Alows to bulk add terms across network
- You can select what sites will be affected
- Works with custom taxonomies
- Doesn't delete
- Doesn't sync
This is something I've done in a last few hours and I have no time for more testing now. Anyway - it works for me! .)
Give it a try. There's also a 'test run' feature implemented so you can check the result before actually doing something.
Update -> Screenshots:
Before action:
After test run:
The plugin linked above adds user interface but pretty much everything important happens in this function:
<?php function mau_add_network_terms($terms_to_add, $siteids, $testrun = false) { // check if this is multisite install if ( !is_multisite() ) return 'This is not a multisite WordPress installation.'; // very basic input check if ( empty($terms_to_add) || empty($siteids) || !is_array($terms_to_add) || !is_array($siteids) ) return 'Nah, I eat only arrays!'; if ($testrun) $log = '<p><em>No need to get excited. This is just a test run.</em></p>'; else $log = ''; // loop thru blogs foreach ($siteids as $blog_id) : switch_to_blog( absint($blog_id) ); $log .= '<h4>'.get_blog_details( $blog_id )->blogname.':</h4>'; $log .= '<ul id="ntlog">'; // loop thru taxonomies foreach ( $terms_to_add as $taxonomy => $terms ) { // check if taxonomy exists if ( taxonomy_exists($taxonomy) ) { // get taxonomy name $tax_name = get_taxonomy($taxonomy); $tax_name = $tax_name->labels->name; //loop thru terms foreach ( $terms as $term ) { // check if term exists if ( term_exists($term, $taxonomy) ) { $log .= "<li class='notice' ><em>$term already exists in the $tax_name taxonomy - not added!</em></li>"; } else { // if it doesn't exist insert the $term to $taxonomy $term = strip_tags($term); $taxonomy = strip_tags($taxonomy); if (!$testrun) wp_insert_term( $term, $taxonomy ); $log .= "<li><b>$term</b> successfully added to the <b>$tax_name</b> taxonomy</li>"; } } } else { // tell our log that taxonomy doesn't exists $log .= "<li class='notice'><em>The $tax_name taxonomy doesn't exist! Skipping...</em></li>"; } } $log .= '</ul>'; // we're done here restore_current_blog(); endforeach; if ($testrun) $log .= '<p><em>No need to get excited. This was just the test run.</em></p>'; return $log; } ?>
I will come back and edit this with more info later (if needed).
It is far from perfect (read known issues in the plugin head).
Any feedback appreciated!-
J'aimebien quand lesgens créent despluginsen réponse à des questions!Vousméritez laprime!I like it when people create plugins in response to questions! You deserve the bounty!
- 3
- 2011-06-03
- Jan Fabry
-
Mercipour votre soutien @Jan Fabry.Je serai heureux si quelqu'un à côté demoitrouve réellement cette chose utile.Thanks for your support @Jan Fabry. I'll be happy if someone beside me will actually find this thing useful.
- 0
- 2011-06-03
- Michal Mau
-
https://github.com/michalmau/Network-Terminatorhttps://github.com/michalmau/Network-Terminator
- 1
- 2014-01-11
- nadavkav
-
- 2011-05-06
La réponse de TheDeadMedic semblebonne,maisj'aifini par adopter une approche différente duproblème. Au lieu de dupliquer lesmêmestermes sur lesnombreux sites,j'aiplutôtfaiten sorte que les autres sites utilisent lestableaux du site d'accueilpour lestermes.
add_action('init', 'central_taxonomies'); function central_taxonomies () { global $wpdb; $wpdb->terms = "wp_terms"; $wpdb->term_taxonomy = "wp_term_taxonomy"; }
Ceci remplace lenom de latable
wp_2_terms
parwp_terms
,etc. Vous devezbien sûr vérifier dans votrebase de donnéespour vous assurer dunomexact destables,quipourrait être différent si vousmodifiez votrepréfixe.Vouspouvez l'exécuter àpartir d'unplugin ou d'unthème (bien queje recommande unplugin). Jepourraipeut-êtrepublier unpluginpour lefaire à unmoment donné. Cette approcheprésente deuxinconvénients:
- Iln'est actif que sur les sitesenfants sur lesquels lepluginest activé. Iln'y a aucunmoyen d'appliquer cela àpartir du siteparent.
- Il s'applique à toutes lestaxonomies,pas seulement à celles sélectionnées.
Cette approcheestflexible -ellepeut être adaptéepourextraire des catégories den'importe quelblog,pas seulement dublog central.
Mise àjour: j'en aifait unplugin,quipeut être activé à l'échelle du site si vousen avezbesoin: Taxonomies centrales de MU
TheDeadMedic's answer looks good, but I ended up taking a different approach to the problem. Instead of duplicating the same terms across the many sites, I instead made the other sites use the home site's tables for terms.
add_action('init', 'central_taxonomies'); function central_taxonomies () { global $wpdb; $wpdb->terms = "wp_terms"; $wpdb->term_taxonomy = "wp_term_taxonomy"; }
This replaces the table name
wp_2_terms
withwp_terms
, etc. You should of course check in your database to make sure of the exact name of the tables, which might be different if you change your prefix.You can run this from either a plugin or a theme (though I recommend a plugin). I may get round to publishing a plugin to do this at some point. There are two downsides to this approach:
- It's only active on child sites that have the plugin activated. There's no way to enforce this from the parent site.
- It applies to all the taxonomies, not just selected ones.
This approach is flexible - it can be adapted to pull categories from any blog, not just the central one.
Update: I've made this into a plugin, which can be activated site-wide if you need it to be: MU Central Taxonomies
-
Il y a ungrosproblème avec cette approche: les relationsentre lesmessageset lestermespeuventne pas être correctes.Latableterm_relationships contient cette relationbasée sur l'ID depublicationet l'ID determe.Maisilesttoujourspossible que lespublications des sous-sites aient lemêmeidentifiant.Lamodification des conditions d'un articlepeut avoir uneffet imprévisible sur un autre article d'un autreblog.There's a big problem with this approach: The relations between posts and terms might not be correct. The table term_relationships contains this relation based on post ID and term ID. But there's always chance that posts in subsites have same ID. Changing terms for 1 post might unpredictable affect on another post in another blog.
- 0
- 2013-11-22
- Anh Tran
-
Correct,latable `term_relationships`ne doitpas êtreincluse.J'ai repéréet corrigé celail y a longtemps dans leplugin,maisje n'aijamaismis àjour cette réponsepour correspondre.Correct, the `term_relationships` table shouldn't be included. I spotted and fixed that long ago in the plugin, but never updated this answer to match.
- 0
- 2013-11-22
- Marcus Downing
-
- 2011-06-01
Oui,c'estpossible.J'ai construit unplugin comme celui-cipour WPMUil y a des lustres (http://natureofmind.org/30/default-categories-for-new-blogs/maisplusprisen charge)plus àjour seraient les deuxplugins suivants: http://wordpress.org/extend/plugins/wpmu-new-blog-defaults/et http://premium.wpmudev.org/project/new-blog-modèle
Yes this is possible. I built a plugin like this for WPMU ages ago (http://natureofmind.org/30/default-categories-for-new-blogs/ but no longer supported) more up-to-date would be the following two plugins: http://wordpress.org/extend/plugins/wpmu-new-blog-defaults/ and http://premium.wpmudev.org/project/new-blog-template
Configuration d'uneinstancemultisite WP - le client dispose d'une ontologie/d'unensemble de catégoriesexistant dans lequelil souhaite classertout le contenu de l'ensemble desblogs.On souhaite également quetoutes lesnouvelles catégories soient ajoutées auniveau du "blog du réseau"et synchronisées avec les autresblogs.
Quelleest lameilleurefaçon deprocéder?