商品についてレビューするサイトで、カスタムフィールドに URL をセットしている場合において、既に以前その URL の記事を書いたか調べたり、要は WordPress のカスタムフィールドに特定の値がセットされている記事が存在するか調べる関数を作りましたので公開しておきます。
コード
functions.php に以下のコードを入れます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function postExist($params = Array()) { if(!isset($params['post_type'])) $params['post_type'] = 'post'; if(!isset($params['meta_key'])) return false; if(!isset($params['meta_value'])) return false; $result = new wp_query(); $result->query("post_type={$params['post_type']}&showpost=1&posts_per_page=1&meta_key={$params['meta_key']}&meta_value={$params['meta_value']}"); if($result->have_posts()) { return true; } else { return false; } } |
使い方
テンプレートの任意の場所で以下のように書きます。
1 2 3 4 5 6 7 8 9 10 11 12 | $result = postExist( Array( 'post_type' => 'post', 'meta_key' => 'url', 'meta_value' => 'url1000' ) ); if($result) { echo 'この商品URLの記事は既に存在しています。'; } else { echo 'この商品URLの記事はまだ存在ません。'; } |
コメント