WordPress のカスタムフィールドの値で記事をソートすることが可能です。
例えばまず参考に、最近記事の一覧にして出力するコードがあります。
1 2 3 4 5 6 | $recent = new wp_query(); $recent->query('post_type=post&showpost=10'); while($recent->have_posts()) { $recent->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } |
これに手を加えて説明しましょう。優先度の高い記事上位10件を表示する一覧を作ります。
カスタムフィールドでキーを priority とし、優先度 000~100 で全ての記事に入力したとします。
その記事を取り出すコードが以下になります。
1 2 3 4 5 6 | $recent = new wp_query(); $recent->query('post_type=post&showpost=10&orderby=meta_value&meta_key=priority&order=DESC')'); while($recent->have_posts()) { $recent->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } |
もちろん WordPress 3.0 から使えるようになったカスタム投稿タイプでも使えます。
プロジェクトというカスタム投稿タイプを作り、カスタムフィールドで progress というキーに 000~100 で進捗状況を入力します。
そして、以下のコードで進捗状況が高いものほど上に表示されるようになります。
1 2 3 4 5 6 7 8 9 10 | $loop = new wp_query(); $loop->query('post_type=project&orderby=meta_value&meta_key=progress&order=DESC'); while($loop->have_posts()) { $loop->the_post(); $progress = get_post_custom_values('progress'); echo '<h3>' . get_the_title() . '</h3>'; echo apply_filters('the_content', get_the_content()); echo '<div class="progress">' . abs($progress[0]) . '%</div>'; } } |
このブログの右側進捗状況はこのコードを応用して作っています。
ソートについて調べる機会があったのでメモしておきます。
ちなみに今回参考にさせていただいた記事は以下です。
WordPress › フォーラム » 投稿をカスタムフィールド値でソートし、更に時系列に並べる
query_postsで指定できるパラメーター | WordPress | understandard.net
ゲンドウ2010-7-28 (水) 13:31:49
カスタムフィールドでの並び替え参考になりました!
決まったフォーマットの記事を検索した場合、
カスタムフィールドの並び替えがしたかったので助かりました^^