• Created a plugin to create Regions as custom Taxonomy.
  • Users will be mapped to Regions using user meta. (from edit user page)
  • posts are displaying based on the assigned region.
  • But the posts count showing differently.

single file plugin is as given below.

configuration:

  1. install
  2. create regions
  3. edit user and assign region
  4. create posts as admin & user – with and without regions
  5. check user post listing

    /*
    Plugin Name: Region Author Mapping
    Plugin URI: 
    Description: Simple plugin limit authors to post based on regions.
    Version: 1.0
    Author: 
    Author URI: 
    */
    
    
    /* Disallow direct access to the plugin file */
    defined('ABSPATH') || die('Sorry, but you cannot access this page directly.');
    
    if (!class_exists('region_author')){
        class region_author{
    
    public  $txtPostType  = 'post';
    public  $txtDomainReg = 'author_regions';
    public  $taxRegions   = 'regions';
    
    /**
     * class constractor
     * @author Ohad Raz
     * @since 0.1
     */
    public function __construct(){
    
        $this->hooks();
    
        if (is_admin()){
            $this->adminHooks();                
        }
    }
    
    /**
     * hooks add all action and filter hooks
     * @since 0.6
     * @return void
     */
    public function hooks(){
    
        // save user field
        add_action( 'personal_options_update', array( $this,'save_extra_user_profile_fields' ));
        add_action( 'edit_user_profile_update', array( $this,'save_extra_user_profile_fields' ));
    
        // add user field
        add_action( 'show_user_profile', array( $this,'extra_user_profile_fields' ));
        add_action( 'edit_user_profile', array( $this,'extra_user_profile_fields' ));
    
        //admin hack for region mapping
        add_filter('parse_query', array( $this,'convert_id_to_term_in_query' ));
        add_action('restrict_manage_posts', array( $this,'filter_post_type_by_taxonomy' ));
    
        //region taxonomy CREATION
        add_filter('init',array($this, 'create_regions_hierarchical_taxonomy'));
    }
    
    /**
     * hooks add all action and filter hooks for admin side
     * 
     * @since 0.7
     * @return void
     */
    public function adminHooks(){
        //remove quick and bulk edit
        global $pagenow;
        if ('edit.php' == $pagenow)
            add_action( 'admin_head-edit.php', array(&$this,'remove_quick_edit')); //add_action('admin_print_styles',array(&$this,'remove_quick_edit'));
    
        //add region metabox
        add_action( 'add_meta_boxes', array( $this, 'add_regions_meta_box' ) );
    }
    
    /**
     * remove_quick_edit
     * @author Ohad   Raz
     * @since 0.1
     * @return void
     */
    public function remove_quick_edit() {
        global $current_user, $pagenow;
        if ($pagenow != 'edit.php')
            return;
        $user_regions = get_user_meta($current_user->ID, '_author_regions', true);
        if (!empty($user_regions) && count($user_regions) > 0) {
        ?>
            <script type="text/javascript">         
                jQuery(document).ready( function($) {
                    $('.cat-checklist.regions-checklist').prev().prev().hide();
                    $('.cat-checklist.regions-checklist').hide();
                });    
            </script>
        <?php
        }
    //            global $current_user;
    //            $user_regions = get_user_meta($current_user->ID,         '_author_regions', true);
    //            if (!empty($user_regions) && count($user_regions) > 0) {
    //                echo '<style>.cat-checklist.regions-checklist{display: none!important;}</style>';
    //            }
    }
    
    /**
     * Adds the meta box container
     * @author Ohad Raz
     * @since 0.1
     */
    public function add_regions_meta_box(){
    
        global $current_user;
        get_currentuserinfo();
        $reg_tax = get_user_meta($current_user->ID, '_author_regions', true);
        if (!empty($reg_tax) && count($reg_tax) > 0){
            //remove default metabox
            remove_meta_box('regionsdiv', 'post', 'side');
            //add user specific regions
            add_meta_box( 
                 'author_regions'
                ,__( 'Regions',$this->txtDomainReg )
                ,array( &$this, 'render_region_meta_box_content' )
                ,$this->txtPostType 
                ,'side'
                ,'low'
            );
        }
    }
    
    /**
     * Render Meta Box content
     * @author Ohad   Raz
     * @since 0.1
     * @return Void
     */
    public function render_region_meta_box_content(){
        global $current_user, $post;
        $postRegionTerms = array();
        get_currentuserinfo();
        $regions = get_user_meta($current_user->ID,'_author_regions',true);
        $regions = (array)$regions;
    
        // Use nonce for verification
        wp_nonce_field( plugin_basename( __FILE__ ), 'author_regions_noncename' );
        if (!empty($regions) && count($regions) > 0){
            if (count($regions) == 1){
                $c = get_term( $regions[0], $this->taxRegions);
    
                echo __('this will be posted in: <strong>',$this->txtDomainReg) . $c->name .__('</strong> Region',$this->txtDomainReg);
                echo '<input name="tax_input[regions][]" type="hidden" value="'.$c->term_id.'">';
            }else{
                echo '<span style="color: #f00;">'.__('Make Sure you select only the regions you want: <strong>',$this->txtDomainReg).'</span><br />';
                $options = get_option('author_regions_option');
                //GETTING SAVED REGIONS OF A POST
                $screen = get_current_screen();
                if ($screen->parent_base == 'edit') {
                    $postRegions = wp_get_post_terms( $post->ID, $this->taxRegions);
                    if($postRegions){
                        foreach ($postRegions as $key => $region) {
                            $postRegionTerms[] = $region->term_id;
                        }
                    }
                }
                foreach($regions as $region ){
                    $c = get_term( $region, $this->taxRegions);
                    $checked = (in_array($region, $postRegionTerms))? ' checked="checked"' : '';
                    echo '<label><input name="tax_input[regions][]" type="checkbox"'.$checked.' value="'.$c->term_id.'"> '.$c->name .'</label><br />';
                }
            }
        }
    }
    
    /**
     * This will generate the regions field on the users profile
     * @author Ohad   Raz
     * @since 0.1
     * @param  (object) $user 
     * @return void
     */
     public function extra_user_profile_fields( $user ){ 
        //only admin can see and save the regions
        if ( !current_user_can( 'manage_options' ) ) { return false; }
        global $current_user;
        get_currentuserinfo();
        if ($current_user->ID == $user->ID) { return false; }
        $select = wp_dropdown_categories(array(
                       'orderby' => 'name',
                       'show_count' => 0,
                       'hierarchical' => 1,
                       'hide_empty' => 0,
                       'echo' => 0,
                       'taxonomy' => $this->taxRegions,
                       'name' => 'author_regions[]'));
        $saved = get_user_meta($user->ID, '_author_regions', true );
        foreach((array)$saved as $c){
            $select = str_replace('value="'.$c.'"','value="'.$c.'" selected="selected"',$select);
        }
        $select = str_replace('<select','<select multiple="multiple"',$select);
        echo '<h3>'.__('Author Regions', 'author_regions').'</h3>
        <table class="form-table">
            <tr>
                <th><label for="author_regions">'.__('Regions',$this->txtDomainReg).'</label></th>
                <td>
                    '.$select.'
                    <br />
                <span class="description">'.__('Select a region to limit an author to post just in that region (use Crtl to select more then one).',$this->txtDomainReg).'</span>
                </td>
            </tr>
            <tr>
                <th><label for="author_regions_clear">'.__('Clear Regions',$this->txtDomainReg).'</label></th>
                <td>
                    <input type="checkbox" name="author_regions_clear" value="1" />
                    <br />
                <span class="description">'.__('Check if you want to clear the region limitation for this user.',$this->txtDomainReg).'</span>
                </td>
            </tr>
        </table>';
    }
    
    /**
     * This will save region field on the users profile
     * @author Ohad   Raz
     * @since 0.1
     * @param  (int) $user_id 
     * @return VOID
     */
    public function save_extra_user_profile_fields( $user_id ) {
        //only admin can see and save the regions
        if ( !current_user_can( 'manage_options') ) { return false; }
    
        //AUTHOR REGION SETTINGS
        update_user_meta( $user_id, '_author_regions', $_POST['author_regions'] );
    
        if (isset($_POST['author_regions_clear']) && $_POST['author_regions_clear'] == 1)
            delete_user_meta( $user_id, '_author_regions' );
    }
    
    /**
     * CREATE REGIONS TAXONOMY
     */
    public function create_regions_hierarchical_taxonomy() {
    
        $labels = array(
            'name' => _x('Regions', 'taxonomy general name'),
            'singular_name' => _x('Region', 'taxonomy singular name'),
            'search_items' => __('Search Regions'),
            'all_items' => __('All Regions'),
            'parent_item' => __('Parent Region'),
            'parent_item_colon' => __('Parent Region:'),
            'edit_item' => __('Edit Region'),
            'update_item' => __('Update Region'),
            'add_new_item' => __('Add New Region'),
            'new_item_name' => __('New Region Name'),
            'menu_name' => __('Regions'),
        );
    
        // Now register the taxonomy
        register_taxonomy($this->taxRegions, array($this->txtPostType), array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'show_admin_column' => true,
            'query_var' => true,
            'rewrite' => array('slug' => 'region'),
        ));
    }
    
    /**
     * Display a custom taxonomy dropdown in admin
     * @author Mike Hemberger
     */
    public function filter_post_type_by_taxonomy() {
        global $typenow;
        if ($typenow == $this->txtPostType) {
            $selected = isset($_GET[$this->taxRegions]) ? $_GET[$this->taxRegions] : '';
            $info_taxonomy = get_taxonomy($this->taxRegions);
            //TO EXCLUDE UNWANTED TAXONOMY TERMS
            $user_regions = array();
            global $current_user;
            $user_regions = get_user_meta($current_user->ID, '_author_regions', true);
            $tax_dropdown = array(
                'show_option_all' => __("All {$info_taxonomy->label}"),
                'taxonomy' => $this->taxRegions,
                'name' => $this->taxRegions,
                'orderby' => 'name',
                'selected' => $selected,
                'include' =>  $user_regions,
                'hide_empty' => false,
            );
            // CREATING THE ADMIN FILTER DROPDOWNS
            wp_dropdown_categories($tax_dropdown);
        }
    }
    
    /**
     * Filter posts by taxonomy in admin
     * @author  Mike Hemberger
     */
    public function convert_id_to_term_in_query($query) {
        global $pagenow, $typenow, $current_user;
        $q_vars = &$query->query_vars;
        $user_regions = get_user_meta($current_user->ID, '_author_regions', true);
        $selected_tax = ((isset($_GET[$this->taxRegions])) && ($_GET[$this->taxRegions] !=0)) ? $_GET[$this->taxRegions] : '';//DROPDOWN FILTER SELECT
        $author_tax = isset($_GET['author']) ? $_GET['author'] : '';
        $tax_slug = array();
        if (($pagenow == 'edit.php') && ($typenow == $this->txtPostType) ) {
            if (!$user_regions) { //ADMIN
                $term = get_term_by('id', $selected_tax, $this->taxRegions);
                $tax_slug[] = $term->slug;
            } else { //OTHER USERS
                $regTaxArray = ($selected_tax)? (explode(',', $selected_tax)) : $user_regions;
                foreach ($regTaxArray as $key => $regTax) {
                    $term = get_term_by('id', $regTax, $this->taxRegions);
                    $tax_slug[] = $term->slug;
                }
            }
            //TO UNSET AUTHOR PARAMETER FOR POST LISTING OF - "Mine"
            if($author_tax){
                unset($q_vars['author']);
                $q_vars['author__in'] = explode(',', $author_tax);
            }
        }
        $q_vars[$this->taxRegions] = implode(',', $tax_slug);            
        $selected_tax = isset($_GET[$this->taxRegions]) ? $_GET[$this->taxRegions] : '';
            }
        }//end class
    }//end if
    //initiate the class on admin pages only
    if (is_admin()){
        $ac = new region_author();
    }
    

It almost killed me. Any help will be highly appreciated. Thanks in Advance!!

Read more here: Region wise Author Post management


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: