Support » Requests and Feedback » 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:

    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);
    ----						$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.)

Viewing 3 replies - 1 through 3 (of 3 total)
  • I should add that lists work as before… “exclude=hidden,7,21,unseen” will exclude posts ids 7 and 21, and posts with slugs “hidden” and “unseen”.

    It’d be great if this got put into the trunk!



    Why has this not been implemented in a WP releaes yet? This should definitely be in there.

    Because people wanting this type of special functionality often codes it themselves. 🙂

    It is this way with MANY things that are in WordPress but the WP team seem to include more and more though.. (and making WP a bloated software :/)

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘get_pages: exclude by slug’ is closed to new replies.