如何检查特定页面是否使用页面模板?

时间:2013-11-12 作者:user2960701

我正在尝试获取一个使用特定模板的页面。我有page\\u id。这是我的代码:

$pids = $wpdb->get_col( $wpdb->prepare(
  "SELECT ID FROM {$wpdb->posts} 
   WHERE post_author = %d AND post_status = \'publish\' 
   AND post_type=\'page\'", $user->ID
) );

foreach($pids as $post_id)
{
   wp_set_post_terms( $post_id, $tag, $taxonomy );

   // I need permalink only if that page use a specific template (say blog.php)
   $permalink_n = get_permalink($post_id);

   set_cimyFieldValue( $user_id, \'HOMEPAGE\', $permalink_n );
}

1 个回复
最合适的回答,由SO网友:gmazzap 整理而成

页面模板在键入的post meta字段中设置\'_wp_page_template\' 所以,不要使用raw$wpdb 查询,您可以运行WP_Query 使用\'author\' 参数和meta_query 要从具有特定模板的特定作者检索页面,请执行以下操作:

$q = new WP_Query( array(
  \'author\' => $user->ID,
  \'post_type\' => \'page\',
  \'meta_query\' => array( array(\'key\' => \'_wp_page_template\', \'value\' => \'blog.php\') )
) );

if ( $q->found_posts > 0 ) {
  foreach ( $q->posts as $post ) {
    // all pages returned have the template `\'blog.php\'`
    wp_set_post_terms( $post->ID, $tag, $taxonomy );
    $permalink_n = get_permalink($post);
    set_cimyFieldValue( $user->ID, \'HOMEPAGE\', $permalink_n );
  }
}
如果您想从作者处检索所有页面,但对所有页面执行某些操作,而对其他页面执行某些操作,则可以

$q = new WP_Query( array(
  \'author\' => $user->ID,
  \'post_type\' => \'page\'
) );

if ( $q->found_posts > 0 ) {
  foreach ( $q->posts as $post ) {

    wp_set_post_terms( $post->ID, $tag, $taxonomy );

    $template = get_post_meta( $post->ID, \'_wp_page_template\', true );

    if ( $template === \'blog.php\' ) {
      $permalink_n = get_permalink($post);
      set_cimyFieldValue( $user->ID, \'HOMEPAGE\', $permalink_n );
    }

  }
}

结束

相关推荐