How to exclude certain entries?

Post here if you need help with SQL.
Post Reply
nyo
Posts: 124
Joined: Mon May 09, 2011 1:55 pm
Location: Mobile

How to exclude certain entries?

Post by nyo »

Hi,

I have a table for pages and I am listing them in the navbar. I want to exclude certain pages, how can I do that?

Here is the function I'm using to get the pages.
function get_pages() {
	$pages = array();
	$query = mysql_query("SELECT 
							`posts`.`id` AS `post_id`,
							`post_title`,
							`post_name`,
							`post_body`
							FROM `posts`
							WHERE `post_type` = 'page'
							ORDER BY `post_id` ASC");
	while ( $row = mysql_fetch_assoc($query)) {
		$pages[] = $row;
	}
	return $pages;
}
and here is the code that I use to list them:
<?php
			foreach (get_pages() as $page) {
			?>
			<li><a href="page.php?p=<?php echo $page['post_name']; ?>"><?php echo $page['post_title']; ?></a></li>
			<?php
			}
		?>
conradk
Posts: 117
Joined: Tue Jul 05, 2011 10:41 pm

Re: How to exclude certain entries?

Post by conradk »

nailyener wrote:and here is the code that I use to list them:
<?php
			foreach (get_pages() as $page) {
			?>
			<li><a href="page.php?p=<?php echo $page['post_name']; ?>"><?php echo $page['post_title']; ?></a></li>
			<?php
			}
		?>
New code that might work:
<?php
$unwanted = array('contact', 'another'); // list the unwanted page 'post_name' s here. In this case, the 'contact' page and the 'another' page would not show up
foreach (get_pages() as $page) {
   if(!in_array($page['post_name'], $unwanted)) {
      echo '<li><a href="page.php?p=' .  $page['post_name'] . '">' . $page['post_title'] . '</a></li>';
   }
}
?>
Tell me if there's any problem.

You could also choose to show only the pages listed in the $unwanted array, by simply removing the ! from the 4th line of my code.

Regards,
CK
Last edited by conradk on Wed Jul 06, 2011 1:21 pm, edited 1 time in total.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: How to exclude certain entries?

Post by jacek »

The $unwanted array should be defined outside of the loop ;)

You could do something similar with just SQL too
SELECT
    `posts`.`id` AS `post_id`,
    `post_title`,
    `post_name`,
    `post_body`
FROM `posts`
WHERE `post_type` = 'page'
AND `post_name` NOT IN ('list', 'of', 'excluded', 'pages')
ORDER BY `post_id` ASC
Image
conradk
Posts: 117
Joined: Tue Jul 05, 2011 10:41 pm

Re: How to exclude certain entries?

Post by conradk »

jacek wrote:The $unwanted array should be defined outside of the loop ;)

Of course..; don't know why I declared it inside of the loop actually. My mistake. Fixed.
Post Reply