web-dev-qa-db-ja.com

メタキーで始まる場合は投稿をクエリする

現在の年+現在の月(つまり201502)で始まるメタキーを持つ投稿を見つける必要がありますが、実際の値にはその月内の任意の日(つまり20150214)を含めることもできます。

本当に難しい部分は、ACFのReapterとDate Pickerフィールドを使ってこれをやろうとしているということです。完全な日付文字列を含む投稿を要求した場合にtrueが返される場所(20150214)に動作していますが、年月だけではどうすればよいかわかりません。

これが私の現在のコードです:

// custom filter to replace '=' with 'LIKE'
function my_posts_where($where) {
    $where = str_replace("meta_key = 'show_times_%_date'", "meta_key LIKE 'show_times_%_date'", $where);
    return $where;
}
add_filter("posts_where", "my_posts_where");
// get results

$this_month = date("Ym") . "14"; // this doesn't work if I remove the . "14"
$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"   => "show_times_%_date",
            "value" => $this_month,
        )
    ),
));

私は本当にmy_posts_whereに混乱していますが、このページからコピーして修正しただけです。

基本的にそれは私が$this_month . $any_dayを言う方法を理解する必要がある「値」オプションです。

ありがとう。

1
JacobTheDev

私はそれを考え出した:

$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"     => "show_times_%_date",
            "value"   => $this_month . "[0-9]{2}",
            "compare" => "REGEXP"
        )
    ),
));
1
JacobTheDev

ここで行う必要があるのは、$this_monthパラメータから日を削除し、LIKE比較(末尾の%を使用)を使用して値をクエリすることだけです-

$this_month = date("Ym");
$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"       => "show_times_%_date",
            "value"     => $this_month . "%",
            "compare"   => "LIKE"
        )
    ),
));

WP_Queryのクラスリファレンスのカスタムフィールドパラメータセクションをご覧ください

0
David Gard