Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active June 17, 2017 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/90b954c3afde140c8573d1934172537f to your computer and use it in GitHub Desktop.
Save tommcfarlin/90b954c3afde140c8573d1934172537f to your computer and use it in GitHub Desktop.
[WordPress] WP_Query Readability Improvements For Yourself (And Others)
<?php
// Assume this is defined within the context of a class.
const MAPPING = [
'employers' => 'page-past-word.php',
'biography' => 'page-biography.php',
'accomplishments' => 'page-csv.php',
];
/* Snip the rest of the class for brevity */
public function map_templates() {
$args = [
'post_type' => array( 'post', 'page' ),
'post_status' => 'publish',
'orderby' => 'ID',
'order' => 'ASC',
'posts_per_page' => -1,
];
$template_query = new \WP_Query( $args );
if ( $template_query->have_posts() ) {
while ( $template_query->have_posts() ) {
$template_query->the_post();
$template_id = get_post_meta( $post_id, 'third_party_template_id', true );
if ( '' === $template_id ) {
continue;
}
// The third-party's template post name can be used to map our custom template.
$template_info = get_post( $template_id );
$template_name = $template_info->post_name;
if ( isset( self::MAPPING[ $template_name ] ) ) {
$template_file = self::MAPPING[ $template_name ];
update_post_meta( $post_id, '_wp_page_template', $template_file );
}
}
}
}
<?php
public function map_page_templates() {
$posts = $this->load_posts_and_pages();
if ( $posts->have_posts() ) {
$this->assign_templates( $posts );
}
}
<?php
private function load_posts_and_pages() {
$args = [
'post_type' => array( 'post', 'page' ),
'post_status' => 'publish',
'orderby' => 'ID',
'order' => 'ASC',
'posts_per_page' => -1,
];
$posts = new \WP_Query( $args );
return $posts;
}
<?php
private function assign_templates( \WP_Query $posts ) {
while ( $posts->have_posts() ) {
$posts->the_post();
$template_id = $this->get_template_id( get_the_ID() );
if ( '' === $template_id ) {
continue;
}
$template_name = $this->get_template_name( $template_id );
if ( null === $template_name ) {
continue;
}
$this->assign_template( get_the_ID(), $template_name );
}
wp_reset_postdata();
}
<?php
private function get_template_id( $post_id ) {
$template_id = get_post_meta( $post_id, 'third_party_template_id', true );
return $template_id;
}
<?php
private function get_template_name( $template_id ) {
$template_info = get_post( $template_id );
$template_name = $template_info->post_name;
if ( isset( self::MAPPING[ $template_name ] ) ) {
return $template_name;
} else {
return null;
}
}
<?php
private function assign_template( $post_id, $template_name ) {
$template_file = self::MAPPING[ $template_name ];
update_post_meta( $post_id, '_wp_page_template', $template_file );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment