• I want to display a list of pages and the template used by each.

    The code I’m currently using is below, but the result is a bit verbose.

    
    <?php
      global $wpdb;
    
    $sql = "SELECT post_title, meta_value
      FROM $wpdb->posts a
      JOIN $wpdb->postmeta b ON a.ID = b.post_id
      WHERE a.post_type = 'page'
      AND a.post_status = 'publish'
      AND b.meta_key = '_wp_page_template'
            ";
    
    $pages = $wpdb->get_results($sql);
    
    echo '<pre>';
    print_r($pages);
    echo '</pre>';
    ?>
    

    The output is…

    
    [1] => stdClass Object
            (
                [post_title] => Notes
                [meta_value] => default
            )
    

    I want to simplify it to something like…

    
    [1] Notes => default
    
    • This topic was modified 9 years, 9 months ago by gulliver.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this:

    
    <?php
    global $wpdb;
    
    $sql = "SELECT post_title, meta_value
      FROM $wpdb->posts a
      JOIN $wpdb->postmeta b ON a.ID = b.post_id
      WHERE a.post_type = 'page'
      AND a.post_status = 'publish'
      AND b.meta_key = '_wp_page_template'
            ";
    
    $results = $wpdb->get_results( $sql );
    $pages = array();
    foreach ( $results as $result ) {
    	$pages[ $result->post_title ] = $result->meta_value;
    }
    
    echo '<pre>';
    print_r( $pages );
    echo '</pre>';
    ?>
    Thread Starter gulliver

    (@gulliver)

    Thanks.

    That’s a lot cleaner and more useful…

    
    Array
    (
    [Notes] => default
    )
    

    If I can find a way to lose the ‘Array’ and the ‘()’ I’ll be happier – and also the square brackets.

    I don’t know if str_replace or preg replace will do it.

    Moderator keesiemeijer

    (@keesiemeijer)

    If you just want to print them out try it with this

    
    <?php
    global $wpdb;
    
    $sql = "SELECT post_title, meta_value
      FROM $wpdb->posts a
      JOIN $wpdb->postmeta b ON a.ID = b.post_id
      WHERE a.post_type = 'page'
      AND a.post_status = 'publish'
      AND b.meta_key = '_wp_page_template'
            ";
    
    $results = $wpdb->get_results( $sql );
    if( !empty( $results ) ) {
    	echo '<ul>';
    	foreach ( $results as $result ) {
    		echo $result->post_title . ': ' . $result->meta_value;
    	}
    	echo '</ul>';
    }
    ?>
    Thread Starter gulliver

    (@gulliver)

    Thanks.
    That’s better.
    This is useful to have a on a private page, so that if I’m tempted to rename templates I can see which pages I then need to resave with the correct template.

    Your help’s appreciated. 😉

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘List pages and templates’ is closed to new replies.