Assign a Category to Crossposted Posts
I was thinking for a long time about adding the settings for it to my plugins, but turns out that there could be a lot of customisations and it would be much better to accomplish it with a filter hook (code snippet). Please check the examples below and also the explanation how to use them.
In case you’re using a multisite version of the plugin:
add_filter( 'rudr_pre_crosspost_terms', function( $terms, $blog_id ) {
if( 3 === $blog_id ) { // target blog ID
$terms = array(
// 'taxonomy name' => array( 'slug1' => array(), ... ),
// in case you do not want any category to be assigned on Site 2
'category' => array(),
// custom taxonomy term slugs on Site 2
'city' => array(
'athens' => array(), // 'term slug' => array()
'istanbul' => array(),
'dubai' => array(),
'colombo' => array(),
),
);
}
return $terms;
}, 10, 2 );We can also assign specific categories (or custom terms) depending on what were the categories of the original post.
add_filter( 'rudr_pre_crosspost_terms', function( $terms, $blog_id ) {
// if our post has 'fruits-original' category
if( array_key_exists( 'fruits-original', $terms[ 'category' ] ) ) {
// remove 'fruits-original'
$terms[ 'category' ] = array_filter(
$terms[ 'category' ],
function( $category_slug ) {
return $category_slug != 'fruits-original';
},
ARRAY_FILTER_USE_KEY
);
// add 'fruits-target'
$terms[ 'category' ][ 'fruits-target' ] = array();
}
// if our post has 'vegetables-original' category
if( array_key_exists( 'vegetables-original', $terms[ 'category' ] ) ) {
// remove 'vegetables-original'
$terms[ 'category' ] = array_filter(
$terms[ 'category' ],
function( $category_slug ) {
return $category_slug != 'vegetables-original';
},
ARRAY_FILTER_USE_KEY
);
// add 'vegetables-target'
$terms[ 'category' ][ 'vegetables-target' ] = array();
}
return $terms;
}, 10, 2 );For a non-multisite version of the plugin:
add_filter( 'rudr_swc_pre_crosspost_terms', function( $terms, $blog_url ){
if( 'https://rudrastyh.com' === $blog_url ) { // target blog URL
// $terms[ taxonomy rest base ] = array( ID1, ID2, ... ),
// in case you do not want any category to be assigned on Site 2
$terms[ 'categories' ] = array();
// term IDs on Site 2 (but for wordpress.com sites – also slugs)
$terms[ 'cities' ] = array( 5, 15, 125, 127 );
}
return $terms;
}, 10, 2 );If you don’t know where to use this piece of code, check this guide.
More details in the video below:
You can also replace one category with another one, just following this example:
add_filter( 'rudr_swc_pre_crosspost_terms', function( $terms, $blog_url ){
// if our post has category with ID = 4 (we're using the ID from the target site!)
if( isset( $terms[ 'categories' ] ) && in_array( 4, $terms[ 'categories' ] ) ) {
// remove category with ID = 4
$terms[ 'categories' ] = array_filter( $terms[ 'categories' ], function( $category_ID ) {
return $category_ID != 4;
} );
// add category with ID = 5
$terms[ 'categories' ][] = 5;
}
return $terms;
}, 10, 2 );