2016-10-15 3 views
1

Wordpressの投稿タイトルを配列に入れたい。Wordpressの投稿タイトルを配列で取得する

私のカスタム投稿タイプには、自分の姓の名前として私の投稿タイトルがあります。私は自分の姓にアルファベット順に投稿を表示し、それを配列に格納したいと考えています。ループでこれをどうやって行うのですか?

答えて

0

ループの外側に配列を作成し、配列を並べ替えるよりも名前で配列を取得することができます。

<?php 
// the array for the names 
$name_array = array(); 

if (have_posts()) { 
    while (have_posts()) { 
     the_post(); 
     $name_array[] = $post->title; 
     // 
     // Post Content here 
     // 
    } // end while 
    if (sizeof($name_array) > 0) { 
     sort($name_array); 
    } // end if for sizeof() 
} // end if 
?> 

もしIF(have_posts()){下でそれを移動させることができるよりも、あなたは、ループの外側アレイを作成できない場合。

重要な注意:このソリューションには現在のループ内の名前しか含まれていないため、クエリがすべての投稿を保持していないか、オフセット/ページングされているなどの場合、配列はあなたのカスタム投稿タイプ。配列内のすべての名前を保持したい場合、ループクエリがすべての投稿を保持していない場合、タイトル(名前)だけを再クエリする必要があります。

0

WP_Queryを使用してカスタム投稿タイプの投稿を取得し、それぞれを実行してタイトルを取得することができます。 WP_Queryを使用して

// just get IDs rather than whole post object - more efficient 
// as you only require the title 
$post_ids = new WP_Query(array(
    'post_type' => 'custom_post_type_name', // replace with CPT name 
    'fields' => 'ids', 
    'orderby' => 'meta_value', 
    'meta_key' => 'surname_field_name' // replace with custom field name 
)); 

$post_titles = array(); 

// go through each of the retrieved ids and get the title 
if ($post_ids->have_posts()): 
    foreach($post_ids->posts as $id): 
     // get the post title, and apply any filters which plugins may have added 
     // (get_the_title returns unfiltered value) 
     $post_titles[] = apply_filters('the_title', get_the_title($id)); 
    endforeach; 
endif; 

は、それはあなたのページのメインループを変更しないという利点を持っている、とあなたはあなたが含まれているカスタムフィールドの名前とともにorderbyを使用して必要とするためにポストを得ることができます姓。

関連する問題