Create a Private Area in WordPress without a Plug-In

By Andrea Marchetti
@marchetti_design

Create a Private Area in WordPress without a Plug-In

We already covered this topic (how create a Private Area with WordPress) but now this new Private Area vol.2 joins more features in one single tool that lets you post private contents:

  • it will be possible to insert contents visible to all users who have access
  • it will be possible to insert contents referred to a sigle user

Users who can log in the area must be registered as subscriber user to the website and they won’t see the backend of wordpress.
When a user log in, he will see a list of different contents, some visible to everyone, others just to him. This new version introduces other improvements to make the installation easier.

Functions.php

First thing, we open functions.php of wordpress and we define a new custom post type private area.


//creo il post type per l’area riservata
add_action(‘init’, ‘crea_contenuti’);
function crea_contenuti() {

$labels = array(
‘name’ => __(‘Area Riservata’),
‘singular_name’ => __(‘Contenuto’),
‘add_new’ => __(‘Aggiungi Contenuto’),
‘add_new_item’ => __(‘Nuovo Contenuto’),
‘edit_item’ => __(‘Modifica Contenuto’),
‘new_item’ => __(‘Nuovo Contenuto’),
‘all_items’ => __(‘Elenco Contenuti’),
‘view_item’ => __(‘Visualizza Contenuti’),
‘search_items’ => __(‘Cerca Contenuto’),
‘not_found’ => __(‘Contenuto non trovato’),
‘not_found_in_trash’ => __(‘Contenuto non trovato nel cestino’),
);

$args = array(
‘labels’ => $labels,
‘public’ => true,
‘rewrite’ => array(‘slug’ => ‘contenuti’),
‘has_archive’ => true,
‘hierarchical’ => false,
‘menu_position’ => 5,
‘supports’ => array(
‘title’,
‘editor’,
‘thumbnail’,
‘comments’
),

);

register_post_type(‘area-riservata’, $args);
}

Then we insert various instructions for the system:

  • make the post of the custom post type private by deafult
  • make the post of the custom post type visible to customers
  • remove the word private from the title of the post
  • hide the bar of wordpress

 


//rendo il post type privato di default
function force_type_private($post)
{
if ($post[‘post_type’] == ‘area-riservata’) {

if ($post[‘post_status’] == ‘publish’) {

$post[‘post_status’] = ‘private’;

}

}
return $post;
}
add_filter(‘wp_insert_post_data’, ‘force_type_private’);

//rendo il post privato visibile al ruolo sottoscrittore
$subRole = get_role( ‘subscriber’ );
$subRole->add_cap( ‘read_private_posts’ );

// rimuovo privato dal titolo
function clean_title($titolo) {
$titolo = esc_attr($titolo);
$cerca = array(
‘#Privato:#’
);
$sostituisci = array(
‘-‘ // Sostituiamo la voce "Privato" con
);
$titolo = preg_replace($cerca, $sostituisci, $titolo);
return $titolo;
}
add_filter(‘the_title’, ‘clean_title’);

//nascondo la barra di wordpress tranne che all’ admin
if (!current_user_can(‘manage_options’)) {
add_filter(‘show_admin_bar’, ‘__return_false’);
}
if (!current_user_can(‘edit_posts’)) {
add_filter(‘show_admin_bar’, ‘__return_false’);
}

We now go to the most important part of the new private area, the custom metabox with the list of users registered to the website.


// creo il metabox per il post type area riservata
function users_meta_init(){
add_meta_box("users-meta", "User Select", "users", "area-riservata", "normal", "high");
}

add_action("admin_init", "users_meta_init");

// lista degli utenti
function users(){
global $post;

$custom = get_post_custom($post->ID);
$users = isset($custom["users"][0]);

$user_args = array(
// cerco solo gli utenti di tipo sottoscrittore
‘role’ => ‘Subscriber’,
‘orderby’ => ‘display_name’
);

// creo la WP_User_Query object
$wp_user_query = new WP_User_Query($user_args);

// richiamo i risultati
$subscribers = $wp_user_query->get_results();

// controllo i risultati
if (!empty($subscribers))
{
// l’attributo di name è la chiave del customfield
echo "<select name=’users’>";

echo ‘<option value="all">Tutti</option>’;

// loop che mostra tutti i sottoscrittori
foreach ($subscribers as $subscriber){

// richiamo i dati dei sottoscrittori
$subscriber_info = get_userdata($subscriber->ID);
$subscriber_id = get_post_meta($post->ID, ‘users’, true);

if($subscriber_id == $subscriber_info->ID) {

$subscriber_selected = ‘selected="selected"’;

} else {

$subscriber_selected = ”;
}

echo ‘<option value=’.$subscriber_info->ID.’ ‘.$subscriber_selected.’>’.$subscriber_info->display_name.'</option>’;
}
echo "</select>";
} else {
echo ‘No authors found’;
}

}

// salvo l’impostazione della lista
add_action(‘save_post’, ‘save_userlist’);

function save_userlist(){
global $post;

if (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE) {
return $post->ID;
}

update_post_meta($post->ID, "users", $_POST["users"]);

}

Using this code we create a metabox with a selectbox inside Users Visibility; this select includes the list of all users registered to the website, by default is set on everything.

By selecting one of the users we assign the content we are posting just to that user. In the visible example for Mario.

Template Protected Area

After the creation of our individual area engine, we have to visualized contents. We create a custom template areariservata.php that we insert in the file of our theme.


<?php
/*
Template Name: Area Riservata
*/
?>
<?php get_header(); ?>

<?php //se l’utente è loggato mostra messaggio di benvenuto e post
if ( is_user_logged_in() ) {?>

<?php //info dell’utente loggato
global $current_user;
get_currentuserinfo();
$my_user = $current_user->user_login ;
$my_user_level = $current_user->user_level ;
$my_user_id = $current_user->ID;
echo ‘Benvenuto, ‘. $my_user;
?>
<hr />

<?php //se l’utente è l’admin mostro tutti i contenuti, altrimenti mostro quelli dell’utente associato al post
if($my_user_level == 10) {

//loop con tutti i contenuti
$wpquery = new WP_Query(array(
‘post_type’ => ‘area-riservata’,
));

} else {

//loop con i contenuti del relativo utente + quelli contrassegnati come all
$wpquery = new WP_Query(array(
‘post_type’ => ‘area-riservata’,
‘meta_query’ => array(
‘relation’ => ‘OR’,
array(
‘key’ => ‘users’,
‘value’ => $my_user_id,
‘compare’ => ‘=’
),

array(
‘key’ => ‘users’,
‘value’ => ‘all’,
‘compare’ => ‘=’
)
)
)
);

}
?>
<?php if ( $wpquery -> have_posts() ) : while ( $wpquery -> have_posts() ) : $wpquery -> the_post(); ?>

<?php //richiamo le info dell’utente associato al post
$user_selected = get_post_meta($post->ID, ‘users’, TRUE);
$user_info = get_userdata($user_selected);
?>

<div class="post">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php the_content(‘Leggi…’);?>

<?php if($user_selected == ‘all’) { ?>

<small><i><?php echo ‘Contenuto per Tutti’; ?></i></small>

<?php } else { ?>

<small><i><?php echo ‘Contenuto per l\’utente: ‘ . $user_info->user_login . "\n"; ?></i></small>

<?php } ?>
</div>
<hr />

<?php endwhile; else: ?>

<div class="post">
<h3>Spicenti, non ci sono contenuti…</h3>
</div>

<?php endif; ?>

<a href="<?php echo wp_logout_url( home_url() ); ?>" title="Logout">Logout</a>

<?php } else { ?>

Area Riservata

<h2>Login</h2>

<?php wp_login_form(); ?>

<?php } ?>

</div>

<?php get_footer(); ?>

Once we set the template in a page of wordpress, when we open the page we will see a form for the log in ( if you’re not logged in).

We access using user and password, the page shows a welcoming message and those post related to users logged in and those visible by everybody.

A brief sum up, the content we post on the private area is visible to all users who have access by default. If we want to post a content just for one user, we only need to select the user in the list Users Visibility and post it.

By this solution, a user will see private content s and others shared with all the private area. There are many applications, apartment block administrator, company’s customer support, school website and more.
Here below available some files for the download, if you have some interesting appliactions or suggestions leave them in a comment.

Stay Tuned!

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Share