get_pages: exclude by slug
-
I made a simple change to get_pages that I think will benefit a lot of people.
The get_pages() function allows you to exclude certain pages from the results, but it requires you to hard-code the page IDs you want to exclude. It’s far more useful to be able to exclude by slug. So I modified the function to do this.
The new syntax is: exclude=<id or slug>. If it’s a number, it’s an ID. If it’s not a number, it’s a slug. So, to get the children of page $papa avoiding any whose slug is “hidden”, do:
$pages = get_pages("parent=$papa&hierarchical=0&exclude=hidden")
and it works like a charm. (Since the id-or-slug convention is used elsewhere too I figured it’d be good here too.)
Here’s the code change:
wp-includes/post.php: 2071: function &get_pages($args = '') { ... 2114: $exclusions = ''; if ( !empty($exclude) ) { $expages = preg_split('/[\s,]+/',$exclude); if ( count($expages) ) { foreach ( $expages as $expage ) { ++++ $exfield = is_numeric($expage) ? 'ID' : 'post_name'; if (empty($exclusions)) ---- $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage); ++++ $exclusions = $wpdb->prepare(" AND ( $exfield <> %s ", $expage); else ---- $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage); ++++ $exclusions .= $wpdb->prepare(" AND $exfield <> %s ", $expage); } } }
(I was making a template for a new web site, and in it there’s a dynamically generated drop-down menu of pages and their subpages. But some of a page’s children are actually page fragments I embed in the parent page with a custom template, like an editable sidebar. I needed to be able to exclude those page fragments without hard-coding their IDs.)
- The topic ‘get_pages: exclude by slug’ is closed to new replies.