Open johnbillion opened 3 years ago
Hi @johnbillion =)
Sharing that we used Authorship on a recent Team 51 project and used the below to re-attribute content when deleting a user. Note, we're only handling posts of type podcast
and post
here, that should be adjusted/generalized for re-use.
/**
* When a user is deleted, and "attribute all content to" another author is chosen,
* assign the Authorship taxonomy relationship to all the re-attributed posts.
*/
function reassign_on_delete( $deleted_user_id, $reassigned_user_id ) {
// If we're not attributing content to another user, bail early.
if ( empty ( $reassigned_user_id ) ) {
return;
}
// Unhook the Authorship function that modifies the query.
remove_action( 'pre_get_posts', 'Authorship\action_pre_get_posts', 9999 );
// Get the taxonomy term IDs that point to the two users.
$old_author_term_object = get_term_by( 'name', $deleted_user_id, 'authorship' );
$old_author_term_id = $old_author_term_object->term_id;
$new_author_term_object = get_term_by( 'name', $reassigned_user_id, 'authorship' );
if ( $new_author_term_object ) {
$new_author_term_id = $new_author_term_object->term_id;
} else {
// No Authorship term was found, so create one.
$new_author_term_array = wp_insert_term( $reassigned_user_id, 'authorship', array( 'slug' => $reassigned_user_id ) );
$new_author_term_id = $new_author_term_array['term_id'];
}
// Get all the posts where this user is the WP Core author.
$args = array(
'post_type' => array( 'podcast', 'post' ),
'posts_per_page' => -1,
'post_status' => 'publish',
'author' => $reassigned_user_id,
);
$author_posts = new \WP_Query( $args );
if ( $author_posts->have_posts() ) {
while ( $author_posts->have_posts() ) {
$author_posts->the_post();
// Check whether this post is associated to any Authorship terms.
$terms = wp_get_post_terms( get_the_ID(), 'authorship' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
if ( ( int ) $deleted_user_id === ( int ) $term->name && ( int ) $deleted_user_id === ( int ) $term->slug ) {
// Remove the old author association.
wp_remove_object_terms( get_the_ID(), $term->slug, 'authorship' );
// Add the new author association.
wp_add_object_terms( get_the_ID(), $new_author_term_id, 'authorship' );
}
}
} else {
wp_add_object_terms( get_the_ID(), $new_author_term_id, 'authorship' );
}
}
}
wp_reset_postdata();
// Re-hook the Authorship function that modifies the query.
add_action( 'pre_get_posts', 'Authorship\action_pre_get_posts', 9999 );
}
Need to document what happens to author attribution when a user is deleted or when a user is removed from a site within a Multisite network.
A future task will cover improving the UX when deleting or removing a user, for example by presenting the option to reassign or remove attribution for the user.