<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Pimp My Site &#187; WordPress</title>
	<atom:link href="http://pimpmysite.net/archives/category/wordpress/feed" rel="self" type="application/rss+xml" />
	<link>http://pimpmysite.net</link>
	<description>Cool stuff on the web</description>
	<lastBuildDate>Tue, 03 Jun 2014 09:17:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>WordPress のややこしいループ処理はこう書けばいい</title>
		<link>http://pimpmysite.net/archives/707</link>
		<comments>http://pimpmysite.net/archives/707#comments</comments>
		<pubDate>Tue, 03 Jun 2014 08:24:50 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=707</guid>
		<description><![CDATA[慣れてないとわかりにくい、慣れてくるとめんどくさい。そんな WordPress のループ処理をシンプルにする方法。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>メインループの場合</h1>
<p>これを、</p>
<pre class="prettyprint lang-php">while ( have_posts() ) :
  the_post();
  // 記事を表示
endwhile;</pre>
<p>こう。</p>
<pre class="prettyprint lang-php">do_action( 'mytheme/loop', '記事出力テンプレート名' );</pre>
<p>もちろん、これだけだとシー&#8230;ンとしてしまうので <code>functions.php</code> に以下のような処理を書いておきます。</p>
<pre class="prettyprint lang-php">/**
 * WordPress main loop.
 *
 * @param string $slug The slug name for the generic template.
 * @param string $name The name of the specialised template.
 */
add_action( 'mytheme/loop', function ( $slug, $name = '' ) {
  while( have_posts() ) :
    the_post();
    get_template_part( $slug, $name );
  endwhile;
} , 10, 2 );</pre>
<p>無名関数を使ってますので PHP 5.3以上の書き方です。5.2 以下の場合はいつものように <code>add_action()</code> の第2引数は関数名にしましょう。<code>$slug</code>, <code>$name</code> は <a target="_blank"  href="http://codex.wordpress.org/Function_Reference/get_template_part"><code>get_template_part()</code></a> と同じ引数です。記事サマリー部分を別テンプレートにするのも <code>single.php</code> なんかに詰め込みすぎないという点でおすすめです。</p>
<p>逆にメンドそうですか？では&#8230;</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>サブループの場合</h1>
<p>これや、</p>
<pre class="prettyprint lang-php">
$query = new WP_Query( $args );
while ( $query->have_posts() ) :
  $query->the_post();
  // 記事を表示
endwhile;
wp_reset_postdata();</pre>
<p>これを、</p>
<pre class="prettyprint lang-php">
$my_posts = get_posts( $args );
foreach ( $my_posts as $post ) :
  setup_postdata( $post );
  // 記事を表示
endforeach;
wp_reset_postdata();</pre>
<p>こう。</p>
<pre class="prettyprint lang-php">do_action( 'mytheme/subloop', $args, '記事出力テンプレート名' );</pre>
<p>ちょっとイケてる気がしてきましたか？もちろん、これもこれだけだとシーーー&#8230;&#8230;ンなので <code>functions.php</code> に下のような処理を書いておきます。</p>
<pre class="prettyprint lang-php">/**
 * Loop post objects.
 *
 * @param array|string query parameters or query string.
 * @param string $slug The slug name for the generic template.
 * @param string $name The name of the specialised template.
 */
add_action( 'mytheme/subloop', function ( $args, $slug, $name = '' ) {
  $query = new WP_Query( $args );

  while ( $query->have_posts() ) :
    $query->the_post();
    get_template_part( $slug, $name );
  endwhile;
  
　// do_action( 'mytheme/pagination', $query );

  wp_reset_postdata();
}, 10, 3 );</pre>
<p>または&#8230;</p>
<pre class="prettyprint lang-php">add_action( 'mytheme/subloop', function ( $args, $slug, $name = '' ) {
  global $post;
    
  $posts = get_posts( $args );
  
  foreach ( $posts as $post ) :
    setup_postdata( $post ) ;
    get_template_part( $slug, $name );
  endforeach;
  
  wp_reset_postdata();
}, 10, 3 );</pre>
<p>これを一回コピペしておけば、実際にループしたい場所に <code>do_action()</code> を書けば済みます。ちなみに <code><a target="_blank" href="http://codex.wordpress.org/Function_Reference/wp_reset_query">wp_reset_query()</a></code> は <code>query_posts()</code> の後処理用なので必要ありません。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>オレオレ親テーマ・フレームワークなどにこういった action の処理を忍ばせておくと、テンプレートファイルはスッキリ見通しが良くなりますね。何だったらよくあるこういうのも、</p>
<pre class="prettyprint lang-php">if ( function_exists( 'wp_pagenavi' ) ) wp_pagenavi();</pre>
<p>こうすれば、</p>
<pre class="prettyprint lang-php">do_action( 'pagination' );</pre>
<p>いいと思いますよ。</p>
<p>以上、アクションベーステーマコーディング部からの提言でした。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/707/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress のタクソノミーを親子順に並べる</title>
		<link>http://pimpmysite.net/archives/696</link>
		<comments>http://pimpmysite.net/archives/696#comments</comments>
		<pubDate>Fri, 09 May 2014 05:15:05 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Plugin]]></category>
		<category><![CDATA[Taxonomy]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=696</guid>
		<description><![CDATA[ビルトイン関数で実現する方法と、並び順を変更するプラグインを紹介します。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>記事に属しているタームを取得する</h1>
<p>以下の関数で、指定した記事に属しているタクソノミーのターム配列を取得できます。</p>
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/get_the_terms" target="_blank">get_the_terms( $post_id, $taxonomy )</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_get_post_terms" target="_blank">wp_get_post_terms( $post_id = 0, $taxonomy = &#8216;post_tag&#8217;, $args = array() )</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_get_object_terms" target="_blank">wp_get_object_terms( $object_ids, $taxonomies, $args = array() )</a></li>
</ul>
<p>なお、上2つは内部で <code>wp_get_object_terms()</code> を利用しています。下2つは <a href="http://codex.wordpress.org/Function_Reference/wp_get_object_terms#Argument_Options" target="_blank">オプション</a> を指定することができます。</p>
<p class="alert alert-danger"><i class="icon-warning-sign"></i> <code>wp_get_post_terms()</code> の引数 <code>$post_id</code> が optional でデフォルト値「0」になっていますが、「0」を与えると空配列を返されて何も取得できないので気をつけましょう。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>タームの親子関係を保持して表示する</h1>
<p>WordPress には、階層（ツリー, 木）構造を持つデータ（オブジェクト）の親子関係を保持しつつ HTML を作成するためのクラスが用意されています。タクソノミー関連では以下のクラスがあります。</p>
<ul>
<li><a href="http://developer.wordpress.org/reference/classes/walker_category/" target="_blank">Walker_Category</a></li>
<li><a href="http://developer.wordpress.org/reference/classes/walker_categorydropdown/" target="_blank">Walker_CategoryDropdown</a></li>
</ul>
<p>        これらはすべて抽象クラス <code><a href="http://codex.wordpress.org/Class_Reference/Walker" target="_blank">Walker</a></code> の派生クラスです。これらのクラスを直接利用する必要は無く、各々以下の関数で利用できます。</p>
<ul>
<li><a href="http://developer.wordpress.org/reference/functions/walk_category_tree/" target="_blank">walk_category_tree()</a></li>
<li><a href="http://developer.wordpress.org/reference/functions/walk_category_dropdown_tree/" target="_blank">walk_category_dropdown_tree()</a></li>
</ul>
<p>walk_category_* 関数に先ほどの関数で取得したタームオブジェクトの配列を渡すと、親子関係が保持された HTML（文字列）を取得できます。第3引数のオプションは省略すると Notice になるので必ず指定します。</p>
<pre class="prettyprint lang-php">$terms = get_the_terms( $post, 'my_taxonomy' );
if ( $terms &#038;&#038; ! is_wp_error( $terms ) ) {
  echo walk_category_tree( $terms, 0, array(
    'use_desc_for_title' => false,
    'style' => 'list',
) );
}</pre>
<pre class="prettyprint lang-php">&lt;select&gt;
&lt;?php
$terms = wp_get_object_terms( $post-&gt;ID, &#039;my_taxonomy&#039; );
if ( $terms &amp;&amp; ! is_wp_error( $terms ) ) {
  echo walk_category_dropdown_tree( $terms, 0, array(
    &#039;show_count&#039; =&gt; false,
    &#039;selected&#039;   =&gt; 0,      // selected term id
  ) );
}
?&gt;
&lt;/select&gt;</pre>
<p class="alert alert-info"><i class="icon-info-sign"></i> ターム取得に失敗した場合（タクソノミーが存在しない等）各関数は <code>false</code>, <code>array()</code>, WP_Errorオブジェクトのいずれかを返します。取得成功を前提にしていると予期せぬ不具合に見舞われることがあるため、成否判定と必要なら例外処理を入れるようにしましょう。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>全タームの親子関係を保持して表示する</h1>
<h2>リスト, ドロップダウン</h2>
<p>        <code><a href="http://developer.wordpress.org/reference/functions/get_terms/" target="_blank">get_terms()</a></code> で全タームを取得して、<a href="#sec2">タームの親子関係を保持して表示する</a> と同様に &#8230; とややこしいことをしなくても、以下のビルトイン関数でできます。</p>
<ul>
<li><a href="http://codex.wordpress.org/Template_Tags/wp_list_categories" target="_blank">wp_list_categories</a>( &#8216;title_li=&#038;taxonomy=my_category&#038;get=all&#8217; )</li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_dropdown_categories" target="_blank">wp_dropdown_categories</a>( &#8216;taxonomy=my_category&#038;get=all&#038;hierarchical=1&#8242; )</li>
</ul>
<p class="alert alert-info"><i class="icon-info-sign"></i> 全タームの取得には <code>'hide_empty' => false</code> が慣習的に指定されがちですが <code>'get' => 'all'</code> の方が意味的に良いように思います。</p>
<h2>チェックボックス</h2>
<p>チェックボックスの HTML も取得可能です。下記の Walker 派生クラスと専用の関数が用意されています。</p>
<ul>
<li><a href="http://developer.wordpress.org/reference/classes/walker_category_checklist/" target="_blank">Walker_Category_Checklist</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_terms_checklist" target="_blank">wp_terms_checklist( int $post_id = 0, array $args = array() )</a></li>
</ul>
<p>これらは <a href="https://core.trac.wordpress.org/browser/tags/3.9.1/src/wp-admin/includes/template.php?rev=28354" target="_blank">wp-admin/includes/template.php</a> 内で定義されているため、公開画面側で利用するには予めインクルードしておく必要があります。</p>
<pre class="prettyprint lang-php">include_once( ABSPATH . &#039;wp-admin/includes/template.php&#039; );
echo &#039;&lt;ul&gt;&#039;, wp_terms_checklist( get_the_ID(), &#039;taxonomy=my_taxonomy&amp;checked_ontop=0&#039;), &#039;&lt;/ul&gt;&#039;;</pre>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>タームの並び順を好きな順番に変更する</h1>
<p>「<strong>記事毎</strong>にタームの並び順を指定する」 <code>term_order</code> という情報が <a href="http://wpdocs.sourceforge.jp/%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9%E6%A6%82%E8%A6%81#.E3.83.86.E3.83.BC.E3.83.96.E3.83.AB.EF.BC.9A_wp_term_relationships" target="_blank">wp_term_relationships</a> テーブルにあります。<code><a href="http://codex.wordpress.org/Function_Reference/register_taxonomy" target="_blank">register_taxonomy()</a></code> のオプションに <code>'sort' => true</code> を指定しておいて <code><a href="http://codex.wordpress.org/Function_Reference/wp_set_object_terms" target="_blank">wp_set_object_terms()</a></code> に<strong>順序付けしたターム</strong>（の ID またはスラッグ）配列を渡すと <code>term_order</code> が設定され、<code>wp_get_object_terms()</code> のオプションに <code>'orderby' => 'term_order'</code> を指定すると指定した順序でタームを取得できます。</p>
<pre class="prettyprint lang-php">register_taxonomy( 'my_taxonomy', 'my_post_type', array(
  'sort' => true,
    :
);

$terms_to_set = array( 'orange', 'melon', 'apple' );
wp_set_object_terms( $post->ID, $terms_to_set, 'my_taxonomy' );
  :

$terms = wp_get_object_terms( $post->ID, 'my_taxonomy', array(
  'orderby' => 'term_order',
  'fields' => 'names',
) );</pre>
<p>でもこれは<strong>記事毎</strong>の並び順なので使いづらいですね。</p>
<h2>並び順の指定にプラグインを使う</h2>
<p>よく利用されるプラグインは以下の2つでしょうか。</p>
<ul>
<li><a href="http://wordpress.org/plugins/ps-taxonomy-expander/">Ps Taxonomy Expander</a></li>
<li><a href="http://wordpress.org/plugins/taxonomy-terms-order/">Category Order and Taxonomy Terms Order</a></li>
</ul>
<p>Category Order and Taxonomy Terms Order は階層ありのタクソノミーのみが対象ですね、何故&#8230; いずれのプラグインも下記の私的な要望には合わないため、自作することにしました。</p>
<ul>
<li><a href="http://wpdocs.sourceforge.jp/%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9%E6%A6%82%E8%A6%81#.E3.83.86.E3.83.BC.E3.83.96.E3.83.AB.EF.BC.9A_wp_terms" target="_blank">wp_terms</a> テーブルに order 用のカラムを追加したくない。</li>
<li>並び順の指定は専用ページではなく、ビルトインの一覧画面でドラッグ＆ドロップしたい。</li>
</ul></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>並び順を変更するプラグインを作った</h1>
<p><a href="http://wordpress.org/plugins/anything-order/" target="_blank">Anything Order</a> というプラグインを作成して、Plugin Directory に登録してみました。詳しくは <a href="http://wordpress.org/plugins/anything-order/" target="_blank">Anything Order の公式プラグインディレクトリ</a> をご覧ください。Anything なのでタクソノミーだけでなく、各種投稿タイプの並び順変更にも使えます。</p>
<dl>
<dt>特長</dt>
<dd>
<ul>
<li>以下の関数で並び順が指定した通りになります。
<ul>
<li><a href="http://codex.wordpress.org/Function_Reference/get_the_terms" target="_blank">get_the_terms()</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_get_post_terms" target="_blank">wp_get_post_terms()</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_get_object_terms" target="_blank">wp_get_object_terms()</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/get_terms" target="_blank">get_terms()</a></li>
<li><a href="http://codex.wordpress.org/Template_Tags/wp_list_categories" target="_blank">wp_list_categories()</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_dropdown_categories" target="_blank">wp_dropdown_categories()</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_terms_checklist" target="_blank">wp_terms_checklist()</a></li>
</ul>
</li>
<li>前項の関数で <code>orderby</code> の指定は不要です。指定がある場合は、並び順 → orderby指定 の順になります。</li>
<li>複数の項目をドラッグ＆ドロップして並び替えできます。</li>
<li>並び順をリセット（クリア）できます。</li>
<li>特定のタクソノミーで並び替えしたくない場合は「表示オプション」でカラムを非表示にします。</li>
<li>並び替えをするには以下の権限が必要です。
<ul>
<li>投稿タイプ：&#8217;edit_others_posts&#8217;</li>
<li>タクソノミー：&#8217;manage_terms&#8217;</li>
</ul>
</li>
<li>プラグイン専用の設定ページはありません。</li>
<li>ビルトインのテーブル構造を変更しません。</li>
</ul>
</dd>
<dt>今後の予定</dt>
<dd>
<ul>
<li>ドラッグ＆ドロップで親子関係を変更したい。</li>
<li>Anything なのでユーザー等（等？）の並び順も変更したいかもしれない。</li>
</ul>
</dd>
</dl>
<p>ご要望・バグレポートをお待ちしてます！</p>
<ul>
<li><a href="http://wordpress.org/support/plugin/anything-order" target="_blank">WordPress.org プラグインサポートフォーラム</a></li>
<li><a href="https://github.com/pimpmysite/anything-order" target="_blank">Github</a></li>
</ul></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>プラグインの告知がしたいだけの記事でしたが、大体のことは WordPress のビルトイン関数で何とかなるようですね。</p>
<dl class="ref">
<dt>参考</dt>
<dd>
<ul>
<li><a href="http://tipsbear.com/wordpress-taxonomy-get-terms-listing-in-order-of-parent-child/" target="_blank">[WordPress]サイドバーに設置したカスタム分類のターム一覧をセレクトメニューにする | tipsBear</a></li>
<li><a href="http://tipsbear.com/wordpress-taxonomy-get-terms-listing-in-order-of-parent-child/" target="_blank">[WordPress]カスタムタクソノミーに親子関係（階層）を持たせ、複数選択したタームの並び順を親＞子の順番に表示する | tipsBear</a></li>
<li><a href="http://ht79.info/2013/05/23/how-to-wordpress-post-relation-terms-list-sort/" target="_blank">【WordPress】記事に設定したカスタムタクソノミーのタームの並び順を好きな並び順にする方法 | ht79.info</a></li>
</ul>
</dd>
</dl></div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/696/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress アンチパターン</title>
		<link>http://pimpmysite.net/archives/589</link>
		<comments>http://pimpmysite.net/archives/589#comments</comments>
		<pubDate>Mon, 24 Mar 2014 05:17:33 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=589</guid>
		<description><![CDATA[実案件やネット上で散見されるバッドプラクティス／バッドノウハウをまとめてみました。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>全部入りカテゴリー <small>All in One Category</small></h1>
<p>ジャンル，地域 &#8230; などサイトに必要となる各種の分類すべてをカテゴリーとして扱う。</p>
<h2>解説</h2>
<p>カスタム分類（タクソノミー）に対する無理解が原因のバッドプラクティスです。下記左側のような分類で設計されてしまうと、カテゴリー一覧などの何でもない処理が非常に混沌としてきます。ジャンル，地域 をカテゴリーのタームではなく、下記右側のようにカスタム分類として定義すると色々とスッキリします。</p>
<div class="row">
<dl class="col box">
<dt>Bad</dt>
<dd>
<ul>
<li>カテゴリー
<ul>
<li>ジャンル
<ul>
<li>和風</li>
<li>洋風</li>
<li>中華風</li>
</ul>
</li>
<li>地域
<ul>
<li>北部</li>
<li>中部</li>
<li>南部</li>
</ul>
</li>
</ul>
</li>
</ul>
</dd>
</dl>
<dl class="col box">
<dt>Good</dt>
<dd>
<ul>
<li>カテゴリー</li>
</ul>
<ul>
<li>ジャンル
<ul>
<li>和風</li>
<li>洋風</li>
<li>中華風</li>
</ul>
</li>
<li>地域
<ul>
<li>北部</li>
<li>中部</li>
<li>南部</li>
</ul>
</li>
</ul>
</dd>
</dl></div>
<h2>ベストプラクティス</h2>
<li><a href="http://wpdocs.sourceforge.jp/%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E5%88%86%E9%A1%9E" target="_blank">カスタム分類（タクソノミー）</a> を使う。</li>
<dl>
<dt>参考</dt>
<dd>
<ul>
<li><a href="http://wpxtreme.jp/how-to-use-cusom-taxonomy-with-wordpress-versions-lower-than-3" target="_blank">WordPress3.0未満でのカスタムタクソノミーの使い方 | wpxtreme</a></li>
</ul>
</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>EXEC-PHP最高 <small>EXEC-PHP Awesome</small></h1>
<p>テンプレートファイル（以下テンプレート）に PHP を書くことに慣れてくると記事本文にも PHP を書きたくなってくるという必然の欲求をズバリ解決するプラグインをネット上で礼賛する。</p>
<h2>解説</h2>
<p>誰もが通る道なのでいたしかたないのですが、ネット上での礼賛は炎上必至です。当該のプラグインは長らく更新されておらず、炎上をきっかけに「入力フォームにコードを書ける ＝ セキュリティリスク」ということが周知されたと思われるので、このアンチパターンを目にすることは無くなるでしょう。</p>
<h2>ベストプラクティス</h2>
<ul>
<li><a href="http://wpdocs.sourceforge.jp/%E3%82%B7%E3%83%A7%E3%83%BC%E3%83%88%E3%82%B3%E3%83%BC%E3%83%89_API" target="_blank">ショートコード</a> を使う。</li>
</ul>
<dl>
<dt>参考</dt>
<dd>
<ul>
<li><a href="http://dogmap.jp/2007/06/03/%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E3%81%84%E3%82%8B-wordpress-plugin/" target="_blank">使用している WordPress Plugin | dogmap.jp</a></li>
<li><a href="http://andask.net/create/exec-php-security-risk.html" target="_blank">Exec-PHP使いは要注意！メリット＜デメリット | アンドウェブ</a></li>
</ul>
</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>関数キライ <small>Function Hater</small></h1>
<p>WordPress に用意されている便利な関数の数々を一切使わない。</p>
<h2>解説</h2>
<p>ビルトイン関数を使うのは負けだと思っているのか、単に関数の存在を知らないのか詳しい原因は不明ですが、中途半端に「PHP できますよ」というエンジニアによく見られます。以下はコーディングの例です。グローバル変数を多用するのも特徴です。</p>
<pre class="prettyprint lang-php">// トップページ判定
// is_home(), is_front_page() を使おう
if ( $_SERVER[&#039;REQUEST_URI&#039;] == &#039;/&#039; )

// カスタム投稿タイプアーカイブ判定
// is_post_type_archive( &#039;info&#039; ) を使おう
if ( $wp_query-&gt;is_archive &amp;&amp; $wp_query-&gt;query_var[&#039;post_type&#039;] == &#039;info&#039; )

// フォームのチェック状態を設定
// checked() を使おう
&lt;input type=&quot;checkbox&quot; name=&quot;cb1&quot; value=&quot;val1&quot;&gt;
</pre>
<h2>ベストプラクティス</h2>
<ul>
<li>車輪を使う。</li>
</ul></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>オプション多過ぎ <small>Options Hell</small></h1>
<p>テーマやプラグインで可能な限りの「設定」を用意する。</p>
<h2>解説</h2>
<p>GUI で簡単設定できて嬉しい反面、コードでの設定や設定のインポート／エクスポートが簡単にできない場合、毎度 GUI 操作による設定に時間を取られることになります。ユーザーのためにと何でもできるようにし過ぎるのが原因ですが、まずは本当にそれをユーザーが必要としているかを考えると良いでしょう。</p>
<h2>ベストプラクティス</h2>
<ul>
<li>減らす。</li>
</ul>
<dl>
<dt>参考</dt>
<dd>
<ul>
<li><a href="https://gettingreal.37signals.com/ch06_Avoid_Preferences.php" target="_blank">Getting Real: Avoid Preferences (by 37signals)</a></li>
<li><a href="http://ja.wikipedia.org/wiki/YAGNI" target="_blank">YAGNI &#8211; Wikipedia</a></li>
<li><a href="http://ja.wikipedia.org/wiki/KISS%E3%81%AE%E5%8E%9F%E5%89%87" target="_blank">KISSの原則 &#8211; Wikipedia</a></li>
</ul>
</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>固定テンプレート <small>Rage Template</small></h1>
<figure class="alignright">
            <img src="http://pimpmysite.net/wp-content/uploads/2014/03/page-attribute-template.jpg" alt="カスタムページテンプレート" width="274" height="192" class="img-polaroid size-full wp-image-592" /><br />
<figcaption>カスタムページテンプレートを指定</figcaption>
</figure>
<p>デザイン・レイアウトが異なる固定ページに対して各々カスタムページテンプレートを作成し、編集画面からいちいちそのテンプレートを指定してめんどくさい固定ページ爆発しろとなる。</p>
<h2>解説</h2>
<p>固定ページの表示にはデフォルトで page.php などのテンプレートが使用されますが、個別にカスタムページテンプレートを指定することもできます。カスタムページテンプレートを作成するには、<a href="http://codex.wordpress.org/Page_Templates#Custom_Page_Template" target="_blank">テンプレートの初めに下記のように PHP のコメントでテンプレート名を指定</a> します。</p>
<pre class="prettyprint lang-php"></pre>
<p><?php
/*
Template Name: My Custom Page Template
*/[/code]
        
<p>このカスタムページテンプレートは、テンプレート内に書くべき HTML や PHP が他と異なり、かつ、<strong>ひな形として複数の固定ページに適用</strong>する場合に使います。それを「デザインが違う固定ページ毎に必要」と誤解しているのがこのバッドプラクティスの原因です。<br /><strong>特定の1ページ専用のテンプレート</strong>を作るなら <code>page-{ページスラッグ}.php</code>, <code>page-{ページID}.php</code> といったファイル名にするだけで、編集画面から指定しなくても自動で適用されます。</p>
<h2>ベストプラクティス</h2>
<ul>
<li>特定の1ページのみに適用するテンプレートは <a href="http://codex.wordpress.org/Page_Templates#Specialized_Page_Template" target="_blank">特定ページテンプレート</a> （適切な日本語訳求む）にする。</li>
<li>スタイルの変更だけで済むなら <code><a href="http://wpdocs.sourceforge.jp/%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%BF%E3%82%B0/body_class" target="_blank">body_class()</a></code> が出力する <code>page-id-{ID}</code> クラスを利用する。<br />ID が扱いづらいなら <code>body_class</code> フィルタで <code>page-{slug}</code> クラスを追加すれば良い。</li>
</ul>
<dl>
<dt>参考</dt>
<dd>
<ul>
<li><a href="http://blog.kohki.tv/bust-wp-vandit/" target="_blank">コーポレートサイトのCMSにWordPressを使うとか言うヤツは眉唾モノ！　WP向きなサイトとそうでないサイト。CMS使い分けのコツ！ | しかたこうきブログ</a></li>
<li><a href="http://webdesignrecipes.com/wordpress-customize-with-template-files/" target="_blank">WordPressをカスタマイズするなら絶対覚えておきたいテンプレートファイルの使い方 | Webデザインレシピ</a></li>
</ul>
</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>プラグイン入れ過ぎ <small>Tons of Plugins</small></h1>
<p>20個以上のプラグインをインストール・有効化してサイトを構築する。</p>
<h2>解説</h2>
<p>クライアントへの提案はプラグインでできることに限られ、プラグイン選定の時間が開発の大部分を占めます。過ぎたるは猶及ばざるが如し、レスポンスが著しく悪いサイトで有効化されていた各種キャッシュ系プラグインをすべてアンストールしたところ常識的なレスポンスに改善された、というネタのような実話もあります。なお、プラグイン依存度は下記のように分類されます。</p>
<div class="offset3 span6">
<table class="table table-striped">
<thead>
<tr>
<th>プラグイン数</th>
<th>呼称</th>
</tr>
</thead>
<tbody>
<tr>
<th>20〜</th>
<td>Junkie</td>
</tr>
<tr>
<th>30〜</th>
<td>Mad</td>
</tr>
<tr>
<th>40〜</th>
<td>Insane</td>
</tr>
<tr>
<th>50〜</th>
<td>Psycho</td>
</tr>
</tbody>
</table></div>
<h2>ベストプラクティス</h2>
<ul>
<li>入れ過ぎない。</li>
</ul></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>固定テンプレートと言いたいだけのエントリですが、いかがでしたでしょうか。問題は多くの場合システムではなく使う側にあるのだと理解することが大事ですね。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/589/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wp_enqueue_script(), wp_enqueue_style() のタグからtype属性を除いてHTML5ぽくしつつ、scriptタグでも条件付きコメントを使えるようにする方法</title>
		<link>http://pimpmysite.net/archives/418</link>
		<comments>http://pimpmysite.net/archives/418#comments</comments>
		<pubDate>Wed, 23 Jan 2013 02:00:02 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=418</guid>
		<description><![CDATA[WordPress テーマの HTML5 化ネタ第1弾です。IE 向け script タグ条件付きコメント対応のおまけつき。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>テーマを HTML5 にしてみた！けれど&#8230;</h1>
<p><code>&lt;!DOCTYPE html&gt;</code> から始まって <code>&lt;section&gt;</code> <code>&lt;article&gt;</code> を駆使して HTML5でテーマを作った！と思ったら、</p>
<ul>
<li><a target="_blank" href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style"><code>wp_enqueue_style()</code></a> して出力される <code>link</code> タグに <code>type="text/css"</code> がついていたり</li>
<li><a target="_blank" href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script"><code>wp_enqueue_script()</code></a> して出力される <code>script</code> タグに <code>type="text/javascript"</code> がついていて</li>
</ul>
<p>げんなりしてしまったこと、ありませんか？ 私はあります。デフォルトのタイプ属性として定義済だから省略できるわけで、あっても間違いではないのですが、HTML ソースがシンプルになって気持ちがいいのも HTML5 の効果だとすれば、無くてもいいものは無い方がいいですね。<br />それじゃぁ、と header.php に直接タグを書こうとすると「それは違うよね」とどこからか声が聞こえてきます&#8230;<br />
        こんなときは WordPress カスタマイズ虎の巻 をひも解いてみましょう。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>その壱 フィルターで書き換えるべし</h1>
<p>スタイルの方は <code>style_loader_tag</code> というフィルターフックで <code>link</code> タグを書き換えることができます。</p>
<pre class="prettyprint lang-php">preg_replace( array( "| type='.+?'\s*|", '| /&gt;|' ), array( ' ', '&gt;' ), $tag );</pre>
<p>こんな感じで良さそうです。type 属性を削除するついでに <code>/&gt;</code>（これは何と呼ぶんでしょうか&#8230;）を <code>&gt;</code> に置換しています。HTML5 的には <code>/&gt;</code> でも良いのですが、無くてもいいものは無い方がいいルールに従ってシンプルに徹します。</p>
<p>一方、スクリプトの方は <code>style_loader_tag</code> に相当するフィルターが無く、タグがいきなり <code>echo</code> されています。困りましたね&#8230; WordPress カスタマイズ虎の巻 を読み進めましょう。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>その弐 クラスを継承すべし</h1>
<p>スクリプト関連の処理は WP_Scripts クラスが担っていて、必要になったときにこれを <code>new</code> したインスタンスがグローバル変数の <code>$wp_scripts</code> に代入されます。ということは、WP_Scripts クラスを継承して処理を書き換えてグローバル変数の <code>$wp_scripts</code> に突っ込めば、こちらの思うがままということになります。というわけで継承してみました。</p>
<script src="https://gist.github.com/4592649.js?file=class-pm-scripts.php"></script><noscript><pre><code class="language-php php">&lt;?php
if ( ! class_exists( 'PM_Scripts' ) ) {
class PM_Scripts Extends WP_Scripts {
    public function __construct() {
        parent :: __construct();
    }
    
    public function print_extra_script( $handle, $echo = true ) {
        if ( !$output = $this-&gt;get_data( $handle, 'data' ) )
            return;

        if ( !$echo )
            return $output;

        echo &quot;&lt;script&gt;\n&quot;;
        echo &quot;&lt;!--\n&quot;;
        echo &quot;$output\n&quot;;
        echo &quot;//--&gt;\n&quot;;
        echo &quot;&lt;/script&gt;\n&quot;;

        return true;
    }
    
    public function do_item( $handle, $group = false ) {
        if ( ! isset( $this-&gt;registered[$handle]) )
            return false;

        if ( 0 === $group &amp;&amp; $this-&gt;groups[$handle] &gt; 0 ) {
            $this-&gt;in_footer[] = $handle;
            return false;
        }

        $obj = $this-&gt;registered[ $handle ];

        if ( false === $group &amp;&amp; in_array($handle, $this-&gt;in_footer, true) )
            $this-&gt;in_footer = array_diff( $this-&gt;in_footer, (array) $handle );

        if ( null === $obj-&gt;ver )
            $ver = '';
        else
            $ver = $obj-&gt;ver ? $obj-&gt;ver : $this-&gt;default_version;

        if ( isset($this-&gt;args[$handle]) )
            $ver = $ver ? $ver . '&amp;amp;' . $this-&gt;args[$handle] : $this-&gt;args[$handle];

        $src = $obj-&gt;src;

        if ( $this-&gt;do_concat ) {
            $srce = apply_filters( 'script_loader_src', $src, $handle );
            if ( $this-&gt;in_default_dir($srce) ) {
                $this-&gt;print_code .= $this-&gt;print_extra_script( $handle, false );
                $this-&gt;concat .= &quot;$handle,&quot;;
                $this-&gt;concat_version .= &quot;$handle$ver&quot;;
                return true;
            } else {
                $this-&gt;ext_handles .= &quot;$handle,&quot;;
                $this-&gt;ext_version .= &quot;$handle$ver&quot;;
            }
        }

        $this-&gt;print_extra_script( $handle );
        if ( !preg_match('|^https?://|', $src) &amp;&amp; ! ( $this-&gt;content_url &amp;&amp; 0 === strpos($src, $this-&gt;content_url) ) ) {
            $src = $this-&gt;base_url . $src;
        }

        if ( !empty($ver) )
            $src = add_query_arg('ver', $ver, $src);

        $src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );

        $end_cond = $tag = '';
        if ( isset( $obj-&gt;extra[ 'conditional' ] ) &amp;&amp; $obj-&gt;extra[ 'conditional' ] ) {
            $tag .= &quot;&lt;!--[if {$obj-&gt;extra['conditional']}]&gt;\n&quot;;
            $end_cond = &quot;&lt;![endif]--&gt;\n&quot;;
        }
    
        $tag .= apply_filters( 'script_loader_tag', &quot;&lt;script src='$src'&gt;&lt;/script&gt;\n&quot;, $handle );
        $tag .= $end_cond;

        if ( $this-&gt;do_concat )
            $this-&gt;print_html .= $tag;
        else
            echo $tag;

        return true;
    }
}
}</code></pre></noscript>
<p>継承ついでに header.php に html5.js の条件付きコメントを直書きしなくて済むようにしておきました。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>スクリプトで条件付きコメントを使う</h1>
<p><code>wp_enqueue_style()</code> したスタイルは条件付きコメントで囲って <code>link</code> タグを出力することができます。<code>wp_enqueue_styles</code> アクションをフックして、</p>
<pre class="prettyprint lang-php">wp_enqueue_style( 'ie7', get_stylesheet_directory_uri() . '/css/ie7.css' );
$GLOBALS['wp_styles']->add_data( 'ie7', 'conditional', 'lte IE 7' );</pre>
<p>とすれば、HTML ソースに、</p>
<pre class="prettyprint lang-php">&lt;!--&amp;#91;if lte IE 7&amp;#93;&gt;
&lt;link rel=&#039;stylesheet&#039; href=&#039;http://example.com/wp-content/themes/mytheme/css/ie7.css?ver=3.5&#039; media=&#039;all&#039;&gt;
&lt;!&amp;#91;endif&amp;#93;--&gt;</pre>
<p>のように出力されます。どちらかというとスクリプトの方が需要がある気がしますが、WordPress はスタイルしかサポートしていないため、上記の PM_Scripts クラスで実装しました。<a target="_blank" href="http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts"><code>wp_enqueue_scripts</code></a> アクションをフックして、</p>
<pre class="prettyprint lang-php">wp_enqueue_script( 'html5', get_stylesheet_directory_uri() . '/js/html5.js' );
$GLOBALS['wp_scripts']->add_data( 'html5', 'conditional', 'lt IE 9' );</pre>
<p>とすれば、HTML ソースに、</p>
<pre class="prettyprint lang-php">&lt;!--&amp;#91;if lt IE 9&amp;#93;&gt;
&lt;script src=&#039;http://example.com/wp-content/themes/mythemes/js/html5.js?ver=3.5&#039;&gt;&lt;/script&gt;
&lt;!&amp;#91;endif&amp;#93;--&gt;</pre>
<p>のように出力されます。</p>
<p class="mute">IE のためだけの対応をしなくてよい未来は、もうすぐやってきますよ&#8230;きっと&#8230;</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>add_data() 豆知識</h1>
<p>使う機会はあまりありませんが WP_Styles, WP_Scripts クラスの <code>add_data()</code> メソッドでいろいろなことができます。</p>
<pre class="prettyprint lang-php">$GLOBALS['wp_styles']->add_data( 'スタイルのID', 'alt', true );
        -----> link タグの rel 属性を rel='alternate stylesheet' にします</pre>
<pre class="prettyprint lang-php">$GLOBALS['wp_styles']->add_data( 'スタイルのID', 'title', 'タイトルですよ' );
        -----> link タグに title='タイトルですよ' を追加します</pre>
<pre class="prettyprint lang-php">$GLOBALS['wp_scripts']->add_data( 'スクリプトのID', 'data', 'JavaScript のコード' );
        -----> script タグの前にインラインでスクリプトを出力します。</pre>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>wp_localize_script() 豆知識</h1>
<p>話題がどんどんそれてますが、Ajax でポストするデータを PHP から JavaScript に渡すときに良く使う関数を紹介します。本来は <a target="_blank" href="http://codex.wordpress.org/Function_Reference/wp_localize_script">wp_localize_script()</a> の名のとおり、スクリプト内で使うテキストをローカライズするためのものだと思われます。なお、この関数は対象とするスクリプトを enqueue した後で呼ぶ必要があります。以下のように書くと、</p>
<pre class="prettyprint lang-php">wp_enqueue_script( 'my_script', get_stylesheet_directory_uri() . '/js/my_script.js' );

$params = array(
    'action'      => 'my_action'
  , '_ajax_nonce' => wp_create_nonce( 'my_action' )
  , 'post_id'     => $post->ID
);

wp_localize_script( 'my_script', 'my_var', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' )
  , 'params'  => $params
) );</pre>
<p>HTML ソースには以下のように出力されます。</p>
<pre class="prettyprint lang-php">&lt;!--
var my_var = { json_encode() された変数の値 };
//--&gt;</pre>
<p>インラインの方は HTML5 ぽく <code>CDATA</code> を無くしてあります。これで my_script.js 内の JavaScript から <code>my_var.ajaxurl</code> <code>my_var.params.action</code> などの値を使うことができますね。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p><code>style_loader_tag</code> フィルターと PM_Scripts クラスの使い方は以下のとおり。ここでは <code>link</code> タグに付く ID も消しています。</p>
<script src="https://gist.github.com/4592649.js?file=functions.php"></script><noscript><pre><code class="language-php php">&lt;?php
add_filter( 'after_setup_theme', 'my_create_scripts' );
function my_create_scripts() {
    require_once( 'class-pm-scripts.php' );
    $GLOBALS['wp_scripts'] = new PM_Scripts;
}

add_filter( 'style_loader_tag', 'my_style_loader_tag' );
function my_style_loader_tag( $tag ) {
    return preg_replace( array( &quot;| type='.+?'\s*|&quot;, &quot;| id='.+?'\s*|&quot;, '| /&gt;|' ), array( ' ', ' ', '&gt;' ), $tag );
}</code></pre></noscript>
<p>WP_Styles, WP_Scripts, enqueue 関連は <code>concat</code>（enqueue された内容を連結して出力）の仕組みもあったりと、結構奥の深いつくりになっていますよ。ぜひコードを読んでみてください。<br />また、今回のクラスを継承してカスタマイズする方法は、適切なフックがない場合に有効なケースが多いです。覚えておいて損はないですよ。</p>
<p>ではまた。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/418/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress でページを表示するまでにインクルードされたテーマ関連 PHP ファイルを一覧する</title>
		<link>http://pimpmysite.net/archives/378</link>
		<comments>http://pimpmysite.net/archives/378#comments</comments>
		<pubDate>Tue, 22 Jan 2013 02:00:11 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=378</guid>
		<description><![CDATA[テンプレートはもちろん include, require, get_template_part(), get_header(), get_footer(), get_sidebar() されたテーマ関連ファイルを全部見せ。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>はじめに</h1>
<p>WordPress のテーマを作成していると、今表示しているのはどのテンプレートファイルなのかを確認したいことがよくあります。テンプレートファイルを確認する方法は色々あるのでわりとすんなり解決するのですが、子テーマだったり <a target="_blank" href="http://wpdocs.sourceforge.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/get_template_part"><code>get_tempate_part()</code></a> を多用していると、このページのこの部分はいったいどの PHP ファイルなんだ？と悩むこともあります。そんなときに便利なロードされたファイル全部見せのスニペットを紹介します。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>get_included_files() / PHP</h1>
<p>PHP では <a target="_blank" href="http://php.net/manual/ja/function.get-included-files.php"><code>get_included_files()</code></a> で、それまでにロードされたすべてのファイルのパスを取得することができます。これを全部表示するととんでもないことになるので、テーマディレクトリ以下のファイルのみに限定するとほぼ、欲しい結果を得られます。テーマディレクトリのパスは <a target="_blank" href="http://codex.wordpress.org/Function_Reference/get_theme_root"><code>get_theme_root()</code></a> で取得できるので、</p>
<ol>
<li><code>get_theme_root()</code> で始まるパスのみ抽出し、</li>
<li>パスから <code>get_theme_root()</code> に一致する部分を削除します。</li>
</ol>
<p>これでロードされたテーマ関連ファイルのみを見やすく表示することができます。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>全部見せスニペット</h1>
<p><code>wp_footer</code> アクションにフックしているので、footer.php で <code>wp_footer()</code> してください。</p>
<script src="https://gist.github.com/4483030.js"></script><noscript><pre><code class="language-php php">&lt;?php
add_action( 'wp_footer', 'pm_trace_included_files' );
function pm_trace_included_files() {
    $includeds = array_values( 
        str_replace( 
            get_theme_root()
          , &quot;&quot;
          , array_filter( 
                get_included_files() 
              , create_function( '$f', 'return 0 === strpos( $f, get_theme_root() );' ) 
             )
        )
    );
    if ( class_exists( 'Debug_Bar_Extender' ) )
        Debug_Bar_Extender::instance()-&gt;trace_var( $includeds, 'Included Files' );  
}</code></pre></noscript>
<p>また、このコードでは <a href="http://wordpress.org/extend/plugins/debug-bar-extender/" title="Plugin Directory を開きます" target="_blank">Debug-Bar-Extender</a> の Variable Lookup ページで確認できるようにしているため、このまま使う場合は <a href="http://wordpress.org/extend/plugins/debug-bar/" title="Plugin Directory を開きます" target="_blank">Debug Bar</a> とあわせてプラグインをインストール・有効化してください。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>ファイルのパスは <code>$includeds</code> に配列で入っているので、Debug Bar を使わずに <code>var_dump()</code> などでお手軽に確認することもできます。せっかくなのでこのサイトの single ページの結果を晒しておきますね。</p>
<pre class="prettyprint lang-php">Included Files = array (
          0 => '/pimpmysite.net/functions.php',
          1 => '/rootstrap/functions.php',
          2 => '/rootstrap/library/class-pm-rootstrap.php',
          3 => '/rootstrap/library/class-pm.php',
          4 => '/rootstrap/library/class-pm-admin.php',
          5 => '/rootstrap/library/class-pm-page.php',
          6 => '/rootstrap/library/class-pm-ogp.php',
          7 => '/rootstrap/library/class-pm-options.php',
          8 => '/rootstrap/library/class-pm-order.php',
          9 => '/rootstrap/library/class-pm-ajax.php',
          10 => '/rootstrap/library/class-pm-scripts.php',
          11 => '/rootstrap/library/class-pm-nav-menus.php',
          12 => '/rootstrap/library/class-pm-less.php',
          13 => '/rootstrap/index.php',
          14 => '/rootstrap/header.php',
          15 => '/rootstrap/parts/html.php',
          16 => '/rootstrap/parts/head.php',
          17 => '/rootstrap/parts/og.php',
          18 => '/rootstrap/parts/og-article.php',
          19 => '/rootstrap/parts/favicon.php',
          20 => '/rootstrap/parts/analytics.php',
          21 => '/rootstrap/parts/afterbody.php',
          22 => '/pimpmysite.net/parts/masthead.php',
          23 => '/pimpmysite.net/parts/navigation.php',
          24 => '/pimpmysite.net/parts/billboard.php',
          25 => '/pimpmysite.net/parts/social.php',
          26 => '/rootstrap/parts/primary.php',
          27 => '/pimpmysite.net/content.php',
          28 => '/pimpmysite.net/sidebar.php',
          29 => '/rootstrap/footer.php',
          30 => '/rootstrap/parts/colophon.php',
        )</pre>
<p>テンプレートは「13：親テーマの index.php」です。これは Debug Bar の WP Query のページでも確認できます。<br /><img src="http://pimpmysite.net/wp-content/uploads/2013/01/1.jpg" alt="Debug Bar | WP Query" class="img-polaroid alignnone size-full wp-image-379" /><br />テンプレートの確認方法は色々紹介されているので参考にしてみてください。</p>
<dl>
<dt>（クエリー）テンプレートを確認する方法</dt>
<dd>
<ul>
<li><a target="_blank" href="https://gist.github.com/4482529">gatespace / view_template_files.php</a></li>
<li><a target="_blank" href="http://wp.tekapo.com/2013/01/14/reveal-template/">Reveal Template | わーどぷれすっ！</a></li>
<li><a target="_blank" href="http://memo.dogmap.jp/2013/01/17/wordpress-lookup-template-name/">[WordPress] 使用しているテンプレート名を取得する | memo.dogmap.jp</a></li>
</ul>
</dd>
</dl></div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/378/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress のコアファイルで見つけたカッコイイ PHP コードの書き方・関数のまとめ</title>
		<link>http://pimpmysite.net/archives/267</link>
		<comments>http://pimpmysite.net/archives/267#comments</comments>
		<pubDate>Mon, 21 Jan 2013 02:00:09 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=267</guid>
		<description><![CDATA[ワンランク上のコーダー()っぽく見えるのでモテること請け合い。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>PHP コード</h1>
<div class="content">
<pre class="prettyprint lang-php">while ( $term = array_shift($terms) )
  $_terms[] = $term->name;</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/get_terms" title="Codex を開きます" target="_blank">get_terms()</a> in wp-includes/taxonomy.php</p>
<p>タームオブジェクトの配列から必要な値（上記ではターム名）のみを配列に入れています。<code>array_shift()</code> でオブジェクトを順に取得しつつ <code>while</code> の条件式にしているところがカッコイイですね。カスタム投稿タイプオブジェクトを取得して <code>slug =&gt; label</code> の配列を作る時などにも便利な書き方です。<a href="http://codex.wordpress.org/WordPress_Coding_Standards" target="_blank">WordPress Coding Standards</a> 的に大丈夫なのかな？と思いましたがセーフみたいです。</p>
<p class="alert alert-danger"><i class="icon-warning-sign"></i> 試しに速度を計測してみたところ、普通に <code>foreach</code> でループさせた方が速かったです。このコはカッコだけでした、ぐぬぬ。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">get_current_screen()->add_help_tab( 〜 );</pre>
<p class="codein">in wp-admin/edit.php</p>
<p>オブジェクトを返す関数から直接プロパティやメソッドにアクセスします。一旦変数に代入するまでもないなら、この書き方で十分ですね。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">function __construct( $manager, $id, $args = array() ) {
  $keys = array_keys( get_class_vars( __CLASS__ ) );
  foreach ( $keys as $key ) {
    if ( isset( $args[ $key ] ) )
      $this->$key = $args[ $key ];
  }</pre>
<p class="codein">WP_Customize_Section::__construct() in wp-includes/class-wp-customize-section.php</p>
<p><code>$args</code> の連想配列でオブジェクトのプロパティ値を設定します。カッコイイ。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">printf( &#039;&lt;a href=&quot;%1$s&quot;&gt;%3$s&lt;/a&gt;&#039;,
  esc_url( get_comment_link( $comment-&gt;comment_ID ) ),
  get_comment_time( &#039;c&#039; ),
  /* translators: 1: date, 2: time */
  sprintf( __( &#039;%1$s at %2$s&#039;, &#039;twentytwelve&#039; ), get_comment_date(), get_comment_time() )
);</pre>
<p class="codein">in wp-content/themes/twentytwelve/functions.php</p>
<p>PHP の値と HTML をあわせて出力するときは、<code>&lt;?php</code> <code>?&gt;</code> で HTML/PHP を切り替えたり、<code>echo</code> で文字列と値を連結するケースが多いですが、いずれも見難いコードになってしまいます。<code>printf/sprintf</code> を使えば、一気に見やすくメンテナンスしやすいコードになりますよ。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">/* translators: If there are characters in your language that are not supported
  by Open Sans, translate this to 'off'. Do not translate into your own language. */
if ( 'off' !== _x( 'on', 'Open Sans font: on or off', 'twentytwelve' ) ) {</pre>
<p class="codein">in wp-content/themes/twentytwelve/functions.php</p>
<p>メッセージカタログ（po/mo ファイル）の記述を config 的な設定値として利用しています。カッコよすぎてシビレますね&#8230;</p>
</div>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>WordPress の便利関数</h1>
<p>WordPress には気の利いた便利でマイナーな関数がたくさんあります。ここではさりげなく使うとカッコイイ関数をいくつか紹介します。</p>
<h2>フィルターにお決まりの値を返す</h2>
<div class="content">
<p>フィルターフックで <code>false</code> <code>array()</code> などありがちな値を返す場合、自分でわざわざフック用の関数を作らなくても既に WordPress に用意されています。</p>
<pre class="prettyprint lang-php">__return_true()
__return_false()
__return_zero()
__return_empty_array()
__return_null()</pre>
<p class="codein">in wp-includes/functions.php</p>
<p>使い方は以下のとおり。シンプルでカッコイイですね。</p>
<pre class="prettyprint lang-php">add_filter( 'filter_name', '__return_true' );</pre>
<h2>日時関連</h2>
<div class="content">
<pre class="prettyprint lang-php">current_time( $type, $gmt = 0 )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/current_time" title="Codex を開きます" target="_blank">current_time()</a> in wp-includes/functions.php</p>
<p>PHP の <code>time()</code> や <code>date()</code> を使って「9時間ずれてるー！」となった経験は誰しもあると思います。これは管理画面の一般設定「タイムゾーン」で指定した現在日時を取得できる関数です。<a href="http://codex.wordpress.org/Function_Reference/date_i18n" target="_blank"><code>date_i18n()</code></a>も内部でこの関数を使っています。</p>
<dl class="well">
<dt>参考：関数によって取得される現在日時の違い</dt>
<dd>
<table class="table table-striped">
<tr>
<th>time()</th>
<td>1779698821</td>
</tr>
<tr>
<th>current_time( &#8216;timestamp&#8217; )</th>
<td>1779731221</td>
</tr>
<tr>
<th>date( &#8216;Y-m-d H:i:s&#8217; )</th>
<td>2026-05-25 08:47:01</td>
</tr>
<tr>
<th>current_time( &#8216;mysql&#8217; )</th>
<td>2026-05-25 17:47:01</td>
</tr>
</table>
</dd>
</dl>
<p class="alert alert-info"><i class="icon-info-sign"></i> <code>$gmt</code> を <code>true</code> にすると Unix タイムスタンプになります。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">human_time_diff( $from, $to = '' )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/human_time_diff" title="Codex を開きます" target="_blank">human_time_diff()</a> in wp-includes/formatting.php</p>
<p>引数に日時を与えると「5分（前）」「2時間（前）」「3日（前）」などの期間表示を返します。管理画面の記事一覧ページの「日時」カラムで使用されていますね。なんと WP 1.5 の時代からあるみたいです。Twitter にインスパイアされたのかと思ってました。</p>
</div>
<h2>フォーム関連</h2>
<div class="content">
<pre class="prettyprint lang-php">checked( $checked, $current = true, $echo = true )
selected( $selected, $current = true, $echo = true )
disabled( $disabled, $current = true, $echo = true )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/checked" title="Codex を開きます" target="_blank">checked()</a>, <a href="http://codex.wordpress.org/Function_Reference/selected" title="Codex を開きます" target="_blank">selected()</a>, <a href="http://codex.wordpress.org/Function_Reference/disabled" title="Codex を開きます" target="_blank">disabled()</a> in wp-includes/general-template.php</p>
<p><code>input</code> 要素などの属性値を簡単に出力できます。<code>if</code> や三項演算子で見難くなりがちなコードをこれらの関数でスッキリ書けます。地味に便利ですね。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">absint( $maybeint )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/absint" title="Codex を開きます" target="_blank">absint()</a> in wp-includes/functions.php</p>
<p>引数の整数の絶対値を返します。PHP の関数だと思ってました&#8230; サニタイズ時に使うと <code>intval()</code> より厳密な感じがしますね。</p>
</div>
<h2>ベタ書き防止</h2>
<p>文字列連結などをベタ書きするより「何をしているのか」を明示する関数を使う方がセマンティックで思慮深そうに見えます。</p>
<div class="content">
<pre class="prettyprint lang-php">trailingslashit( $string )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/trailingslashit" title="Codex を開きます" target="_blank">trailingslashit()</a> in wp-includes/formatting.php</p>
<p>        <code>$string</code> の最後にスラッシュが付いていてもいなくても、確実に1つだけスラッシュを付けます。安易に <code>. '/'</code> とすると <code>string//</code> となることがあるのでこの関数を使いましょう。関数名が長いのは気にしないでください&#8230;</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">path_join( $base, $path )</pre>
<p class="codein">in wp-includes/functions.php</p>
<p>        <code>rtrim($base, '/') . '/' . ltrim($path, '/')</code> を返します。パスの連結をベタ書きするよりスマートですね。</p>
</div>
<div class="content">
<pre class="prettyprint lang-php">zeroise( $number, $threshold )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/zeroise" title="Codex を開きます" target="_blank">zeroise()</a> in wp-includes/formatting.php</p>
<p>        指定した桁数になるよう数字の前に0をパディングします。0詰めをベタ書きするよりクレバーですね。</p>
</div>
<h2>カッコイイ関数</h2>
<p>関数そのものがカッコイイですよ。</p>
<pre class="prettyprint lang-php">wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false )</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/wp_filter_object_list" title="Codex を開きます" target="_blank">wp_filter_object_list()</a> in wp-includes/functions.php</p>
<p>オブジェクト配列の中から、条件に合うオブジェクトを抽出します。<a href="http://codex.wordpress.org/Function_Reference/get_post_types" target="_blank"><code>get_post_types()</code></a> の内部でも使われていますね。これを使っているとすごい人に見えます。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>セマンティックな定数</h1>
<pre class="prettyprint lang-php">define( 'MINUTE_IN_SECONDS', 60 );
define( 'HOUR_IN_SECONDS',   60 * MINUTE_IN_SECONDS );
define( 'DAY_IN_SECONDS' ,   24 * HOUR_IN_SECONDS   );
define( 'WEEK_IN_SECONDS',    7 * DAY_IN_SECONDS    );
define( 'YEAR_IN_SECONDS',  365 * DAY_IN_SECONDS    );</pre>
<p class="codein">in wp-includes/default-constants.php</p>
<p>1日を秒数で指定するときは <code>60 * 60 * 24</code> より <code>DAY_IN_SECONDS</code> の方がわかりやすくてカッコイイですね。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>デバッグに使えるコード</h1>
<p>WordPress コアファイルではありませんが、<a href="http://wordpress.org/extend/plugins/debug-bar/" title="Plugin Directory を開きます" target="_blank">Debug Bar</a>, <a href="http://wordpress.org/extend/plugins/debug-bar-extender/" title="Plugin Directory を開きます" target="_blank">Debug-Bar-Extender</a> などのデバッグ用プラグインを使いこなしているとカッコイイですね。</p>
<pre class="prettyprint lang-php">Debug_Bar_Extender::instance()->trace_var( $value, $var_name = false )</pre>
<p>変数の値を <code>&lt;pre /&gt; 付き var_dump()</code> で確認できます。<code>var_dump()</code> の代替以上の使い勝手ですよ。実際に使う場合は、プラグインが停止されていてもエラーにならないように <code>if ( class_exists( 'Debug_Bar_Extender' ) )</code> で判定をしましょう。</p>
<dl class="well">
<dt>Debug Bar 関連情報</dt>
<dd>
<ul>
<li><a href="http://dogmap.jp/2011/03/08/wordpress-debug-bar/" target="_blank">WordPress 開発に便利なプラグイン Debug Bar | dogmap.jp</a></li>
<li><a href="http://www.kakunin-pl.us/2012/10/making-debug-bar/">Debug Barプラグインをもっと有効活用してみよう！ | カクニンプラスのweb日誌</a></li>
</ul>
</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>番外編</h1>
<p>使いどころがわからない関数や不要かもしれない関数も結構あります。カッコよくないかもしれないので注意してください。</p>
<pre class="prettyprint lang-php">is_new_day()</pre>
<p class="codein"><a href="http://codex.wordpress.org/Function_Reference/is_new_day" title="Codex を開きます" target="_blank">is_new_day()</a> in wp-includes/functions.php</p>
<p>一覧表示時（ループ中）に記事の公開日付が変わったかどうかを判定するようですが、どこからも使われていません。ちなみに <code>the_date()</code> 内部で関連するグローバル変数を操作していて、そこで new day 判定も直接しています。何故 <code>is_new_day()</code> を使わない&#8230;</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>これらの他にも <a href="http://codex.wordpress.org/Function_Reference/antispambot" title="Codex を開きます" target="_blank"><code>antispambot()</code></a> <code>size_format()</code> ファイル操作関数など、個人的には使う機会がないですが、いざ必要となったときにあると便利な関数やコードのヒントが WordPress にはたくさんあります。ソースや Codex を眺めていると新たな発見があるかもしれませんよ。以上、全然まとめきれていませんがこの辺りで失礼します。</p>
<p>ではまた。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/267/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WordPress で記事の公開期間を簡単コントロール！カスタムフィールドに開始・終了日時を指定するだけでOKのクラス</title>
		<link>http://pimpmysite.net/archives/174</link>
		<comments>http://pimpmysite.net/archives/174#comments</comments>
		<pubDate>Sat, 29 Dec 2012 08:47:35 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=174</guid>
		<description><![CDATA[カスタムフィールドに記事の公開日時範囲を指定するだけで幸せになれます。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>大規模・企業サイトでは必須</h1>
<p>公開日時の範囲指定はマストですよね&#8230; プラグインを使うと独自の UI が追加されてしまって、あぁカスタマイズ工数が&#8230; とつらくなることもあります。そんなときに便利な、管理画面を作り込んである場合でも、WordPress デフォルトのままでも、カスタムフィールドで公開範囲の日時さえ指定すればあとはよろしくやってくれるクラスを作りました。</p>
<script src="https://gist.github.com/4405428.js?file=class-pm-schedule-post.php"></script><noscript><pre><code class="language-php php">&lt;?php
if ( ! class_exists( 'PM_Schedule_Post' ) ) {
class PM_Schedule_Post {
    protected $from  = '';
    protected $to    = '';
    protected $label = '';
    
    public function __construct( $from, $to, $label = 'expired' ) {
        $this-&gt;from  = $from;
        $this-&gt;to    = $to;
        $this-&gt;label = $label;
        
        add_action( 'init'                  , array( $this, 'register'        ) );    
        add_filter( 'wp_insert_post_data'   , array( $this, 'set_future'      ), 10, 2 );
        add_action( 'transition_post_status', array( $this, 'schedule_expire' ), 10, 3 );
        add_action( 'expire_post'           , array( $this, 'expire_post'     ) );
    }

    public function register() {
        register_post_status( 'expired', array(
            'label'       =&gt; $this-&gt;label,
            'protected'   =&gt; true,
            'label_count' =&gt; _n_noop( 
                $this-&gt;label . ' &lt;span class=&quot;count&quot;&gt;(%s)&lt;/span&gt;', 
                $this-&gt;label . ' &lt;span class=&quot;count&quot;&gt;(%s)&lt;/span&gt;'
            ),
        ) );        
    }   
    
    protected function get_date( $date, $opt = '' ) {
        if( $opt )
            $date = strtotime( $opt, strtotime( $date ) );
        else 
            $date = strtotime( $date );
            
        return date( 'Y-m-d H:i:s', $date );
    }
    
    protected function get_meta( $key ) {
        $val = '';
        
        if ( isset( $_POST[$key] ) ) {
            $val = $key = $_POST[$key];
        } elseif( isset( $_POST['meta'] ) ) {
            foreach ( (array) $_POST['meta'] as $meta ) {
                if ( $key == $meta['key'] ) {
                    $val = $meta['value'];
                    break;
                }
            }
        }

        return $val;
    }
    
    public function set_future( $data, $postarr ) {
        $from = $this-&gt;get_meta( $this-&gt;from );
        $to   = $this-&gt;get_meta( $this-&gt;to   );

        if ( $from &amp;&amp; $to &amp;&amp; $from &gt; $to )
            return;

        $now  = date( 'Y-m-d H:i:59' );

        if ( ! empty( $from ) ) {
            $start     = $this-&gt;get_date  ( $from  );
            $start_gmt = get_gmt_from_date( $start );
            
            if ( mysql2date( 'U', $start_gmt, false ) &gt; mysql2date( 'U', $now, false ) ) {
                $data['post_date'    ] = $start;
                $data['post_date_gmt'] = $start_gmt;
                $data['post_status'  ] = 'future';              
            }
        }
        if ( 'future' != $data['post_status'] &amp;&amp; ! empty( $to ) ) {
            $end       = $this-&gt;get_date  ( $to  );
            $end_gmt   = get_gmt_from_date( $end );
            
            if ( mysql2date( 'U', $end_gmt, false ) &gt; mysql2date( 'U', $now, false ) ) {
                $data['post_modified'    ] = current_time( 'mysql' );
                $data['post_modified_gmt'] = $now;
                $data['post_status'      ] = 'publish'; 
            }
        }

        return $data;   
    }
    
    public function schedule_expire( $new_status, $old_status, $post ) {
        $to = $this-&gt;get_meta( $this-&gt;to );
        if ( empty( $to ) )
            $to = $post-&gt;{$this-&gt;to};
        
        if ( 'publish' == $new_status &amp;&amp; ! empty( $to ) ) {
            wp_clear_scheduled_hook( 'expire_post', array( $post-&gt;ID ) );
            wp_schedule_single_event( 
                strtotime( get_gmt_from_date( $this-&gt;get_date( $to ) ) . ' GMT' ),
                'expire_post',
                array( $post-&gt;ID ) 
            );
        }
    }
    
    public function expire_post( $post_id ) {
        global $wpdb;
    
        $post = get_post($post_id);
    
        if ( empty($post) )
            return;
    
        if ( 'publish' != $post-&gt;post_status )
            return;

        $wpdb-&gt;update( $wpdb-&gt;posts, array( 'post_status' =&gt; 'expired' ), array( 'ID' =&gt; $post_id ) );
    }
}
}</code></pre></noscript>
<p>このコードをテーマの functions.php またはプラグインファイルに貼り付けるか、ファイル自体をインクルードします。クラスを有効にするには以下のように書きます。</p>
<pre class="prettyprint lang-php">add_action( 
    'after_setup_theme'
  ,  create_function( '', 'new PM_Schedule_Post( "pubstart", "pubend", "label" );' )
);</pre>
<p>PHP 5.3以上なら以下のようにも書けますね。</p>
<pre class="prettyprint lang-php">add_action( 'after_setup_theme'，function() {
    new PM_Schedule_Post( "pubstart", "pubend", "label" );
});</pre>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>クラスの引数</h1>
<p>        <code>PM_Schedule_Post()</code> の引数は以下の通りです。</p>
<dl class="param-list">
<dt>pubstart</dt>
<dd><em>string</em> <em>required</em> 公開開始日時用カスタムフィールドの名前（キー）英数字推奨</dd>
<dt>pubend</dt>
<dd><em>string</em> <em>required</em> 公開終了日時用カスタムフィールドの名前（キー） 英数字推奨</dd>
<dt>label</dt>
<dd><em>string</em> <em>optional</em> 公開終了ステータスの表示用ラベル</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>このクラスは <code>expired</code> という投稿ステータスを追加します。画像の例では表示用ラベルを”公開終了”にしています。<br /><img class="img-polaroid alignnone size-full wp-image-178" alt="1" src="http://pimpmysite.net/wp-content/uploads/2012/12/13.jpg"></p>
<p>日時の指定の仕方による動作の違い：</p>
<dl>
<dt>公開開始日時のみ指定</dt>
<dd>未来日時なら予約投稿になります。過去日時なら公開済になります。</dd>
<dt>公開終了日時のみ指定</dt>
<dd>即時公開され、指定日時に公開終了になります。</dd>
<dt>公開開始日時と公開終了日時の両方指定</dt>
<dd>指定された日時の期間だけ公開になります。</dd>
</dl>
<p>イレギュラーな指定で困ったことになった場合はお知らせください！</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/174/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WordPress のカスタム投稿タイプが多い時に管理画面メニューでの並び順をまとめるスニペット</title>
		<link>http://pimpmysite.net/archives/164</link>
		<comments>http://pimpmysite.net/archives/164#comments</comments>
		<pubDate>Fri, 28 Dec 2012 15:30:13 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=164</guid>
		<description><![CDATA[WordPress のちょっと気になるツッこまれポイントを未然に防ぎます。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>カスタム投稿タイプを多用する事例</h1>
<div id="attachment_165" style="width: 260px" class="wp-caption alignright"><img src="http://pimpmysite.net/wp-content/uploads/2012/12/12.jpg" alt="並び替えます" width="250" height="auto" class="img-polaroid size-full wp-image-165" /><p class="wp-caption-text">（カスタム）投稿タイプをまとめたい</p></div>
<p>増えています。3つ、4つは当り前。最近は10を超えるカスタム投稿タイプを駆使するサイトも見かけます。そんなときにちょっと気になるのが管理画面でのメニューの並び順。特に「メディア」はすごく中途半端な位置にいますね&#8230;</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>気にしなければいいんですが</h1>
<p>        制作者が気にしなくてもお客様は気になり出したら止まりません。プラグインでメニューを消したり並び替えたりもできますが、年末なので頭の体操的にスニペットを書いてみました。これで投稿タイプを上へまとめてしまいます。</p>
<script src="https://gist.github.com/4398585.js"></script><noscript><pre><code class="language-php php">&lt;?php
add_filter( 'custom_menu_order', '__return_true' );
add_filter( 'menu_order'       , 'pm_menu_order' );  

function pm_menu_order( $menu_order ) {
    $menu = array();

    foreach ( $menu_order as $key =&gt; $val ) {
        if ( 0 === strpos( $val, 'edit.php' ) )
            break;
            
        $menu[] = $val;
        unset( $menu_order[$key] );
    }
    
    foreach ( $menu_order as $key =&gt; $val ) {
        if ( 0 === strpos( $val, 'edit.php' ) ) {
            $menu[] = $val;
            unset( $menu_order[$key] );
        }
    }

    return array_merge( $menu, $menu_order );
}</code></pre></noscript>
<p><code>custom_menu_order</code> フィルターで <code>true</code> を返すと、メニューの順序を変えるための <code>menu_order</code> フィルターが呼ばれるので、お好みで順序を変更します。もっとスマートに書けるよ！とかあったら教えてください。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/164/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress でバナーウィジェットを簡単作成〜シンプルなアップローダーの利用例</title>
		<link>http://pimpmysite.net/archives/137</link>
		<comments>http://pimpmysite.net/archives/137#comments</comments>
		<pubDate>Thu, 27 Dec 2012 15:02:02 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=137</guid>
		<description><![CDATA[シンプルなアップローダーを使ってバナーウィジェットを作ってみました。プラグインにもできますよ。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>ウィジェットを作る</h1>
<p>WordPress のウィジェットは作りがパターン化されていて見よう見まねで作ることができるので、ウィジェットの作り方自体は省略します。<a href="http://pimpmysite.net/archives/9">シンプルなアップローダー</a> のアップロード機能をウィジェットに追加するには、<code>PM_Uploader</code> を <code>new</code> して、フォーム内で <code>PM_Uploader :: render()</code> と書くだけです。ただし、ウィジェット内でシンプルなアップローダーを使う場合は、第2引数にウィジェットオブジェクトを与えます。</p>
<script src="https://gist.github.com/4388521.js?file=class-pm-widget-banner.php"></script><noscript><pre><code class="language-php php">&lt;?php
if ( ! class_exists( 'PM_Widget_Banner' ) ) {

add_action( 'widgets_init', create_function( '', 'new PM_Uploader; register_widget(&quot;PM_Widget_Banner&quot;);' ) );

require_once( 'class-pm-uploader.php' );

class PM_Widget_Banner extends WP_Widget {

    function __construct() {
        $widget_ops = array( 'description' =&gt; 'バナーを表示します' );
        parent::__construct( 'banner', 'バナー', $widget_ops );
    }

    function widget( $args, $instance ) {
        $blank = isset( $instance['blank'] ) ? $instance['blank'] : 0;
        $url   = isset( $instance['url'  ] ) ? $instance['url'  ] : '';
        $alt   = isset( $instance['alt'  ] ) ? $instance['alt'  ] : '';
        $image = isset( $instance['image'] ) 
            ? wp_get_attachment_image( intval( $instance['image'] ), 'full', false, array( 'alt' =&gt; $alt ) )
            : '';
            
        if ( 0 !== strpos( $url, 'http') )
            $url = trailingslashit( home_url( $url ) );
            
        printf(
            '&lt;a href=&quot;%1$s&quot;%2$s&gt;%3$s&lt;/a&gt;'
          , esc_url( $url )
          , ( $blank ? ' target=&quot;_blank&quot;' : '' )
          , $image
        );
    }

    function update( $new_instance, $old_instance ) {
        $instance['blank'] = intval( $new_instance['blank'] );
        $instance['image'] = intval( $new_instance['image'] );
        $instance['alt'  ] = strip_tags( $new_instance['alt'] );
        $instance['url'  ] = $new_instance['url'];
        return $instance;
    }

    function form( $instance ) {
        $blank = isset( $instance['blank'] ) ? intval    ( $instance['blank'] ) : 0;
        $image = isset( $instance['image'] ) ? intval    ( $instance['image'] ) : 0;
        $alt   = isset( $instance['alt'  ] ) ? strip_tags( $instance['alt'  ] ) : '';
        $url   = isset( $instance['url'  ] ) ? esc_attr  ( $instance['url'  ] ) : '';
?&gt;
        &lt;div&gt;
            &lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id('image'); ?&gt;&quot;&gt;Image:&lt;/label&gt;
            &lt;?php PM_Uploader :: render( array( 'media_id' =&gt; $image, 'field_id' =&gt; 'image' ), $this ) ?&gt;
        &lt;/div&gt;
        &lt;p&gt;
            &lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id('alt'); ?&gt;&quot;&gt;Alt:&lt;/label&gt;
            &lt;input type=&quot;text&quot; class=&quot;widefat&quot; id=&quot;&lt;?php echo $this-&gt;get_field_id('alt'); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name('alt'); ?&gt;&quot; value=&quot;&lt;?php echo $alt; ?&gt;&quot; /&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id('url'); ?&gt;&quot;&gt;URL:&lt;/label&gt;
            &lt;input type=&quot;text&quot; class=&quot;widefat&quot; id=&quot;&lt;?php echo $this-&gt;get_field_id('url'); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name('url'); ?&gt;&quot; value=&quot;&lt;?php echo $url; ?&gt;&quot; /&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id('blank'); ?&gt;&quot;&gt;
            &lt;input type=&quot;checkbox&quot; id=&quot;&lt;?php echo $this-&gt;get_field_id('blank'); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name('blank'); ?&gt;&quot; value=&quot;1&quot; &lt;?php checked($blank) ?&gt;/&gt; Open New Window&lt;/label&gt;
        &lt;/p&gt;
&lt;?php
    }
}
}
</code></pre></noscript>
<p>このファイルを <a target="_blank" href="https://github.com/pimpmysite/PM_Uploader">PM_Uploader</a> と同じフォルダに入れて、テーマまたはプラグインからインクルードします。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>プラグインにする</h1>
<p>上のファイルをインクルードするプラグイン用のファイルを書くだけです。</p>
<script src="https://gist.github.com/4388521.js?file=pm-widget-banner.php"></script><noscript><pre><code class="language-php php">&lt;?php
/*
Plugin Name: Pimp My Banner Widget
Plugin URI: http://pimpmysite.net/archives/137
Description: Banner widget.
Author: Pimp My WP
Author URI: http://pimpmysite.net
Version: 1.0
*/

require_once( 'class-pm-widget-banner.php' );
</code></pre></noscript>
<p>プラグインフォルダに適当なフォルダを作って、以上のファイルを全部入れればバナーウィジェットプラグインのできあがりです。<br /><img src="http://pimpmysite.net/wp-content/uploads/2012/12/1.jpg" alt="1" class="img-polaroid alignnone size-full wp-image-154"><br />［管理画面｜プラグイン｜インストール済プラグイン］で「Pimp My Banner Widget」を有効化すればバナーウィジェットが使えるようになります。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/137/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress 標準のメディアマネージャーは使わない！クライアントワークで重宝するシンプルUIの簡単アップローダー</title>
		<link>http://pimpmysite.net/archives/9</link>
		<comments>http://pimpmysite.net/archives/9#comments</comments>
		<pubDate>Mon, 24 Dec 2012 00:59:27 +0000</pubDate>
		<dc:creator><![CDATA[pmsadmin]]></dc:creator>
				<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://pimpmysite.net/?p=9</guid>
		<description><![CDATA[Plupload を利用した、ドラッグ&#038;ドロップまたはファイルを選択するだけのアップローダーをご紹介します。]]></description>
				<content:encoded><![CDATA[<section class="section" itemProp="articleSection">
<div class="container">
<h1>新しいメディアマネージャー</h1>
<p><img class="img-polaroid alignright size-full wp-image-33" alt="2012122501" src="http://pimpmysite.net/wp-content/uploads/2012/12/2012122501.jpg" width="261" height="auto" />先日リリースされた WordPress 3.5 の目玉機能のひとつに、<a href="http://ja.wordpress.com/" target="_blank">WordPress.com</a> で一足先に導入されていた「<a href="http://ja.blog.wordpress.com/2012/11/30/seamless-media/" target="_blank">新しいメディアマネージャー</a>」があります。<br />
        これまでとはケタ違いに洗練された UI から WordPress の進化をひしひしと感じるわけですが、CMS としてお客様に納品する場合には、その高機能さが逆に使いづらいという場面があるかもしれません。</p>
<p>今どきの案件なら、カスタム投稿タイプやカスタムフィールドを多用して管理画面を作り込むことが多いのではないでしょうか。画像アップロード時の操作感がそれらと異なると、マニュアルの整備や運用時のトラブルなど、作る側・使う側双方にデメリットとなるおそれもなきにしもあらず。周囲に馴染む、必要最低限のさりげないアップローダーがあれば&#8230;と思ったことはありませんか？</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>シンプルなアップローダー</h1>
<p>そんなシンプルなアップローダーを作ってみました。フォーム内に <code>PM_Uploader :: render( $args )</code> と書くだけで、画像をアップロードする部分（ドロップゾーン）を出力できます。以下はカスタムフィールドに使った例です。</p>
<div class="wp-caption">
<p class="wp-caption-image"><img src="http://pimpmysite.net/wp-content/uploads/2012/12/14-728x326.jpg" alt="カスタムフィールドへの簡単アップローダー設置例" width="728" height="326" class="alignnone size-large wp-image-703"></p>
<div class="wp-caption-text">カスタムフィールドへの簡単アップローダー設置例</div>
</div>
<p>アップローダーの外観が WP 3.5 以前のままなのとドロップゾーンが狭いのは大目にみてください&#8230; ファイルをドロップゾーンに直接ドロップするか、「ファイルを選択してください」のリンクをクリックしてファイルを選択するだけでアップロードされます。アップロード処理自体は、WP に同梱されている <a target="_blank" href="http://www.plupload.com/">Plupload</a> をそのまま利用しています。</p>
<p><img src="http://pimpmysite.net/wp-content/uploads/2012/12/3.jpg" alt="サムネイル上に表示される削除ボタン" width="150" height="auto" class="img-polaroid alignleft size-full wp-image-99" />アップロードした画像のサムネイル上にポインタを移動すると削除ボタンが出てきます。これをクリックすると、画像を完全に削除します。「削除しますか？」の確認はありませんので、注意してください。</p>
</div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>シンプルなアップローダーの使い方</h1>
<ol>
<li>ファイルを<a target="_blank" href="https://github.com/pimpmysite/PM_Uploader" title="GitHubのリポジトリを開きます">こちら</a>からダウンロードします。</li>
<li>ダウンロードしたファイル一式を、テーマまたはプラグインのフォルダ内にコピーします。<br />
            サブフォルダ内にまとめても大丈夫です。</li>
<li>テーマまたはプラグインから「class-pm-uploader.php」をインクルードします。</li>
<li>フォームの HTML を出力するところで <code>PM_Uploader :: render( $args )</code> と書きます。パラメータの詳細は後述。</li>
<li>POST されたデータ <code>$_POST['field_name']</code> に画像 ID が入ります。</li>
</ol></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>シンプルなアップローダーのパラメータ</h1>
<p>$args には連想配列かクエリストリングの書式で以下のパラメータを与えます。</p>
<dl class="param-list">
<dt>field_id</dt>
<dd><em>string</em> <em>required</em> アップロードコンテナ要素に付けられる ID。</dd>
<dt>field_name</dt>
<dd><em>string</em> <em>optional</em> 画像の ID を持つ input フィールドの name 属性値。省略時は <code>field_id</code> と同じになります。</dd>
<dt>media_id</dt>
<dd><em>integer</em> <em>optional</em> アップロード済の画像があればその ID。ドロップゾーンの下にサムネイルを表示します。</dd>
</dl></div>
</section>
<section class="section" itemProp="articleSection">
<div class="container">
<h1>まとめ</h1>
<p>画像アップロード機能のあるテーマやプラグインで利用していただくと、ユーザー操作の手間が減って喜ばれるかもしれません。ぜひお試しください。<br />フィードバックもお待ちしています。バグの指摘や改善点、要望などいただけると嬉しいです。</p>
<p>ではまた。</p>
</div>
</section>
]]></content:encoded>
			<wfw:commentRss>http://pimpmysite.net/archives/9/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
