WordPress.org

Ready to get started?Download WordPress

Forums

get_pages: exclude by slug (4 posts)

  1. richcon
    Member
    Posted 5 years ago #

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

  2. richcon
    Member
    Posted 5 years ago #

    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!

  3. keithnorm
    Member
    Posted 4 years ago #

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

  4. Tommie Hansen
    Member
    Posted 4 years ago #

    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 :/)

Topic Closed

This topic has been closed to new replies.

About this Topic