1

I'm kind lost on how to do that. Let me explain my problem.

I have an admin who can define a lot of categories. Then i want him to be able to attribute through the dashboard multiple categories to each user.

Then when a user will make a post (custom post type: news and others, using both the same taxonomy "Categories") it will take the one defined by the admin in his profil.

So for exemple, the admin go to the dashboard to user_1. He can now see the list of categories (has it is when you add a post) he select wich categories this user belongs to. Let's take : -restaurant -- italian

When user_1 is log in and add now a news he souldn't be able to select categories but whenpublishing the news it will be add in those 2 categories "restaurant" and "italian"

Any one has a solution i've have been trying for 3 days now :(

Thanks in advance for your help

Regards

Adrien

PS: Sorry for my bad english i'm trying to do my best.

Here is my actually custom post in my functions

// Post type
add_action('init', 'postType');
// Custom Post type
function postType()
{
// News
register_post_type('news', array(
    'label' => 'News',
    'labels' => array(
        'name' => 'News',
        'singular_name' => 'News',
        'all_items' => 'Toutes les News',
        'add_new_item' => 'Ajouter une News',
        'edit_item' => 'Éditer la News',
        'new_item' => 'Nouvelle News',
        'view_item' => 'Voir la News',
        'search_items' => 'Rechercher parmi les News',
        'not_found' => 'Pas de News',
        'not_found_in_trash' => 'Pas de News dans la corbeille'
    ),
    'public' => true,
    'capability_type' => 'post',
    'supports' => array(
        'title',
        'editor',
        'excerpt',
        'thumbnail',
        'author'
    ),
    'has_archive' => true, 
    'menu_icon' => 'dashicons-welcome-write-blog',
    'hierarchical' => true,
    'taxonomies' => array('category'),
    'capabilities' => array(
        'publish_posts' => 'publish_news',
        'edit_posts' => 'edit_news',
        'edit_others_posts' => 'edit_others_news',
        'delete_posts' => 'delete_news',
        'delete_others_posts' => 'delete_others_news',
        'read_private_posts' => 'read_private_news',
        'edit_post' => 'edit_news',
        'delete_post' => 'delete_news',
        'read_post' => 'read_news'
    ),

));

// News
register_post_type('etablissement', array(
    'label' => 'Etablissement',
    'labels' => array(
        'name' => 'Etablissement',
        'singular_name' => 'Etablissements',
        'all_items' => 'Tous les Etablissements',
        'add_new_item' => 'Ajouter un Etablissement',
        'edit_item' => 'Éditer l\'Etablissement',
        'new_item' => 'Nouvel Etablissement',
        'view_item' => 'Voir l\'Etablissement',
        'search_items' => 'Rechercher parmi les Etablissements',
        'not_found' => 'Pas d\'Etablissement',
        'not_found_in_trash' => 'Pas d\'Etablissement dans la corbeille'
    ),
    'public' => true,
    'capability_type' => 'post',
    'supports' => array(
        'title',
        'editor',
        'excerpt',
        'thumbnail',
        'author'
    ),
    'show_ui' => true,
    'has_archive' => true, 
    'menu_icon' => 'dashicons-admin-multisite',
    'hierarchical' => true,
    'taxonomies' => array('category'),
    'capabilities' => array(
        'publish_posts' => 'publish_letablissements',
        'edit_posts' => 'edit_letablissements',
        'edit_others_posts' => 'edit_others_letablissements',
        'delete_posts' => 'delete_letablissements',
        'delete_others_posts' => 'delete_others_letablissements',
        'read_private_posts' => 'read_private_letablissements',
        'edit_post' => 'edit_letablissements',
        'delete_post' => 'delete_letablissements',
        'read_post' => 'read_letablissements',
       // 'create_posts' => false,
       'create_posts' => false,
    ),


));





// News
register_post_type('montreux', array(
    'label' => 'Montreux',
    'labels' => array(
        'name' => 'Montreux',
        'singular_name' => 'Montreux',
        'all_items' => 'Touts les articles Montreux',
        'add_new_item' => 'Ajouter un article Montreux',
        'edit_item' => 'Éditer l\'article Montreux',
        'new_item' => 'Nouvel article Montreux',
        'view_item' => 'Voir l\'article Montreux',
        'search_items' => 'Rechercher parmi les articles Montreux',
        'not_found' => 'Pas d\'article Montreux',
        'not_found_in_trash' => 'Pas d\'article Montreux dans la corbeille'
    ),
    'public' => true,
    'capability_type' => 'post',
    'supports' => array(
        'title',
        'editor',
        'excerpt',
        'thumbnail',
        'author'
    ),
    'has_archive' => true, 
    'menu_icon' => 'dashicons-admin-home',
    'hierarchical' => true,
    'taxonomies' => array('category'),
    'capabilities' => array(
    'edit_post' => 'edit_montreux',
    'edit_posts' => 'edit_montreux',
    'edit_others_posts' => 'edit_other_montreux',
    'publish_posts' => 'publish_montreux',
    'read_post' => 'read_montreux',
    'read_private_posts' => 'read_private_montreux',
    'delete_post' => 'delete_montreux',
    'delete_published_posts' => 'delete_published_montreux'
),

));


 flush_rewrite_rules();

 }

Thanks

  • So in short you need to preselect "restaurant" and "italian" categories for a specific user role, right ? – CodeMascot Jan 5 '17 at 8:49
  • yes that will be greate. But the best will be that it is force so the user cannot select those categories and it should be automatic :) so we could hide the categories section to not be visible for users. Only the admin should be able to see it. I was thinking maybe i can do that with css so preselect should be fine Thanks for your help – Adrien de Bosset Jan 5 '17 at 8:50
1

Ok thanks for your help i manage to make it work :

1 : When admin go inside user option page he can select wich categories he is into 2 : Then this user is creating a news and we can see i'm hiding the category box 3 : Then if we check we can see the news has the categories set from the one choose in the user

1 2

So let me give my code maybe it will help some one once :)

    function restrict_user_form_enqueue_scripts($hook) {
    if ( ! in_array($hook, array('profile.php', 'user-edit.php' )))
        return;
    wp_enqueue_script('jquery');
    wp_enqueue_script( 'jquery.multiple.select', get_template_directory_uri() . '/js/jquery.multiple.select.js' );
    wp_register_style( 'jquery.multiple.select_css', get_template_directory_uri() . '/css/multiple-select.css', false, '1.0.0' );
    wp_enqueue_style( 'jquery.multiple.select_css' );
}


add_filter('pre_option_default_category', 'jam_change_default_category');

function jam_change_default_category($ID) {
    // Avoid error or heavy load !
    if ( ! is_user_logged_in() )
        return $ID;
    $user_id = get_current_user_id();
    $restrict_cat = get_user_meta( $user_id, '_access', true);
    if ( is_array($restrict_cat) ) {
        return reset($restrict_cat);
    } else {
        return $ID;
    }
}

/**
* Exclude categories which arent selected for this user.
*/
add_filter( 'get_terms_args', 'restrict_user_get_terms_args', 10, 2 );

function restrict_user_get_terms_args( $args, $taxonomies ) {
    // Dont worry if we're not in the admin screen
    if (! is_admin() || $taxonomies[0] !== 'category')
        return $args;
    // Admin users are exempt.
    $currentUser = wp_get_current_user();
    if (in_array('administrator', $currentUser->roles))
        return $args;

    $include = get_user_meta( $currentUser->ID, '_access', true);

    $args['include'] = $include;
    return $args;
    //var_dump($include);
}
// Display and save data in admin dashboard
function restrict_user_form( $user ) {
    // A little security
    if ( ! current_user_can('add_users'))
        return false;
    $args = array(
        'show_option_all'    => '',
        'orderby'            => 'ID',
        'order'              => 'ASC',
        'show_count'         => 0,
        'hide_empty'         => 0,
        'child_of'           => 0,
        'exclude'            => '',
        'echo'               => 0,
        'hierarchical'       => 1,
        'name'               => 'allow',
        'id'                 => '',
        'class'              => 'postform',
        'depth'              => 0,
        'tab_index'          => 0,
        'taxonomy'           => 'category',
        'hide_if_empty'      => false,
        'walker'             => ''
    );

    $dropdown = wp_dropdown_categories($args);
    // We are going to modify the dropdown a little bit.
    $dom = new DOMDocument();
    //$dom->loadHTML($dropdown, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $dom->loadHTML( mb_convert_encoding($dropdown, 'HTML-ENTITIES', 'UTF-8') );
    $xpath = new DOMXpath($dom);
    $selectPath = $xpath->query("//select[@id='allow']");

    if ($selectPath != false) {
        // Change the name to an array.
        $selectPath->item(0)->setAttribute('name', 'allow[]');
        // Allow multi select.
        $selectPath->item(0)->setAttribute('multiple', 'yes');

        $selected = get_user_meta( $user->ID, '_access', true);
        // Flag as selected the categories we've previously chosen
        // Do not throught error in user's screen ! // @JamViet
        if ( $selected )
        foreach ($selected as $term_id) {
            // fixed delete category make error !
            if (!empty($term_id) && get_the_category_by_ID($term_id) ){
                $option = $xpath->query("//select[@id='allow']//option[@value='$term_id']");
                $option->item(0)->setAttribute('selected', 'selected');
            }
        }
    }
?>
    <h3><?php _e('Catégories de cet utilisateur', 'restrict-author-posting'); ?></h3>
    <table class="form-table">
        <tr>
            <th><label for="access"><?php _e('Choisissez les categories', 'restrict-author-posting') ?>:</label></th>
            <td>
                <?php echo $dom->saveXML($dom);?>
                <span class="description"><?php _e('', 'restrict-author-posting') ?></span>
            </td>
        </tr>

    </table>
    <table class="form-table">
        <tr>
            <th><label for="access"><?php _e('Voir seulement ces fichiers medias', 'restrict-author-posting') ?></label></th>
            <td>
                    <fieldset>
                    <legend class="screen-reader-text"><span><?php _e('Oui', 'restrict-author-posting') ?></span></legend>
                    <label for="_restrict_media">
                    <input type="checkbox" <?php checked (get_user_meta($user->ID, '_restrict_media', true), 1, 1 ) ?> value="1" id="_restrict_media" name="_restrict_media">
                <?php _e('Oui', 'restrict-author-posting') ?></label>
                    </fieldset>
            </td>
        </tr>
    </table>
    <script>
    <!--
        jQuery('select#allow').multipleSelect();
    -->
    </script>
<?php
}


// Restrict Save Data
function restrict_save_data( $user_id ) {
    // check security
    if ( ! current_user_can( 'add_users' ) )
        return false;
    // admin can not restrict himself
    if ( get_current_user_id() == $user_id )
        return false;
    // and last, save it
    if ( ! empty ($_POST['_restrict_media']) ) {
        update_user_meta( $user_id, '_restrict_media', $_POST['_restrict_media'] );
    } else {
        delete_user_meta( $user_id, '_restrict_media' );
    }
    if ( ! empty ($_POST['allow']) ) {
        update_user_meta( $user_id, '_access', $_POST['allow'] );
    } else  {
        delete_user_meta( $user_id, '_access' );
    }
}

// Remove meta box for non admin    
function remove_metaboxes() {
remove_meta_box( 'categorydiv','news','normal' );
remove_meta_box( 'categorydiv','etablissement','normal' );
}

// Save Category News
function save_category_news($post_ID, $post) {
    $currentUser = wp_get_current_user();
    $cat = get_user_meta( $currentUser->ID, '_access', true);
    $cat = array_map('intval', $cat);
    wp_set_object_terms($post_ID, $cat, 'category', true);

}

// Save Category Etablissement
function save_category_etablissement($post_ID, $post) {
    $currentUser = wp_get_current_user();
    $cat = get_user_meta( $currentUser->ID, '_access', true);
    $cat = array_map('intval', $cat);
    wp_set_object_terms($post_ID, $cat, 'category', true);

}
// Action let's go
add_action( 'admin_enqueue_scripts', 'restrict_user_form_enqueue_scripts' );
add_action( 'show_user_profile', 'restrict_user_form' );
add_action( 'edit_user_profile', 'restrict_user_form' );
add_action( 'personal_options_update', 'restrict_save_data' );
add_action( 'edit_user_profile_update', 'restrict_save_data' );
add_action( 'save_post_news', 'save_category_news', 10, 3 );
add_action( 'save_post_etablissement', 'save_category_etablissement', 10, 3 );
add_action( 'admin_menu', 'remove_metaboxes');
0

Here is your solution-

add_action( 'save_post_news', 'the_dramatist_save_post_cat', 10, 3 );

function the_dramatist_save_post_cat($post_ID, $post, $update) {
    $u_id = get_current_user_id();
    if ($u_id == 1) { // Here put your user ID.
        $cats = array( 108, 109 ); // Here put "restaurant" and "italian" category ID
        // setting the category
        wp_set_object_terms($post_ID, $cats, "category", TRUE);
    }
}

Hope that helps.

  • It's good start but how can admin select wich categories in wants for each user. Because there is almost 120 categories et it has to be dynamic :( – Adrien de Bosset Jan 5 '17 at 9:04
  • So you need to a GUI or backend for selecting users with categories ? Oh that a lot of work my friend. – CodeMascot Jan 5 '17 at 9:06
  • See my updated answer. I've added user ID check. Now make it dynamic and merge it to your system. – CodeMascot Jan 5 '17 at 9:10
  • each user has different category so yes i need a GUI in the backend :P or maybe plug it with a plugin ? – Adrien de Bosset Jan 5 '17 at 9:55
  • because i have like 40 users and then they would be probably more same for categories now 150 categories and admin can add more later so it has to be automatic – Adrien de Bosset Jan 5 '17 at 10:12

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.