首页 视频课程 主题开发课程第08章、自定义字段 WordPress按字段查询文章操作方法

WordPress按字段查询文章操作方法

2023-06-11 / 493阅

为了按字段查询文章,需要先了解WordPress的查询操作。

WordPress通过WP_Query类进行查询操作,该类支持按照一系列参数来进行查询。其中,使用meta_key和meta_value参数可以指定按照某个字段和对应的值来查询文章。

示例代码:

$args = array(
    'post_type' => 'post', // 文章类型
    'meta_key' => 'custom_field', // 自定义字段名
    'meta_value' => 'custom_value', // 自定义字段值
);
$query = new WP_Query( $args ); // 执行查询

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // 输出文章标题和内容
        $title = get_the_title();
        $content = get_the_content();
        echo "## {$title}nn{$content}nn";
    }
}

wp_reset_postdata(); // 重置文章数据 

上述代码通过查询自定义字段名为custom_field且值为custom_value的文章,并返回标题和内容的markdown格式。其中,需要注意的是,如果要查询多个自定义字段,可以使用meta_query参数,并设置relation参数的值为and。

$args = array(
    'post_type' => 'post', // 文章类型
    'meta_query' => array(
        'relation' => 'and', // 多个查询条件用and连接
        array(
            'key' => 'custom_field1',
            'value' => 'custom_value1',
        ),
        array(
            'key' => 'custom_field2',
            'value' => 'custom_value2',
        ),
    ),
); 

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录