Archive

Posts Tagged ‘menu’

Create a menu for private pages and posts in Wordpress

July 21st, 2008

Recently I was working on a project that required a members menu on sidebar. Idea was to mark some pages and posts in WordPress as a private ones. All those marked as private are not to be accessible to all others, unregistered users, or even some registered that do not belong to some assigned role. WordPress default behavior for posts and pages is not to show up on menu if you are not registered user, which is good. However, another WordPress default behavior is to show only private posts on sidebar menu while logged in. Meaning that pages marked as private do not show up on the menu when logged in. This is not so good. I needed a solution that will list private pages on my menu as well. After few minutes of unsuccessful Google search, i decided to write my own solution. It really wasn’t that difficult. It all came down to two existing WordPress functions, current_user_can(’some_role’) and $wpdb->get_results($some_query).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php 
 
function private_menu($menu_type, $user_role) {
 
/*
 
$menu_type = all		->show pages and post mixed on menu
$menu_type = post	->show posts only
$menu_type = page	->show pages only
 
*/
 
if(current_user_can($user_role)) {
 
	global $wpdb;
	$html = null;
 
	if($menu_type != 'all') {
		$menu_query = "post_status='private' AND post_type='". $menu_type ."'";
	}
 
	else if($menu_type == 'all') {
		$menu_query = "post_status='private'";
	}
 
	$query = "SELECT * FROM $wpdb->posts WHERE ". $menu_query;
	$pages = $wpdb->get_results($query);	
 
 
	$html .= '<ul>';
	foreach ($pages as $page) {
 
		if($page->post_parent == 0) {$html .= '<li class="page_item"><a href="'. $page->guid. '" title="">'. $page->post_title .'</a></li>';}
		else if($page->post_parent != 0) {
 
			$html .= '<ul class="children">';
			$html .= '<li class="page_item"><a href="'. $page->guid. '" title="">'. $page->post_title .'</a></li>';
			$html .= '</ul>';
		}
	}
	$html .= '</ul>';
 
 
	return $html;
 
}
 
else {
 
	$html = '<p>We are sorry, but only <strong>'. $user_role .'</strong> role user can access this area</p>';
	# return $html;
	return false;
}
}
?>

PHP, WordPress , ,