Custom field to array?

时间:2012-10-12 作者:Mark R

我有一个posts查询,它按ID查询posts,但希望通过插入自定义字段来选择这些posts。这是查询,我想将自定义字段放在哪里:

$query_args = array(\'post_type\'=>\'post\', \'post_status\'=>\'publish\', \'include\' => \'483,454, CUSTOM FIELD HERE\', \'orderby\' => \'date\', \'order\' => \'ASC\');
更多信息:自定义字段是listids,并传入include。但不起作用。

<?php
&listids = get_post_meta($post->ID, \'list_array\', true);
$query_args = array(\'post_type\'=>\'post\', \'post_status\'=>\'publish\', \'include\' => \'echo $listids;\', \'orderby\' => \'date\', \'order\' => \'ASC\');
$query_posts = get_posts($query_args);
$last_query = end($query_posts);
foreach ($query_posts as $post) : setup_postdata($post); ?> 

1 个回复
最合适的回答,由SO网友:Ben HartLenn 整理而成

我假设您(或用户)将在posts自定义字段中输入post ID,以逗号分隔,例如:11,13,34,5411, 13, 34, 54.

然后,您需要做的就是为加载的帖子获取自定义字段值,用逗号(,)分解自定义字段值:然后,您将有一个很好的数组传递到include 参数以下是一个显示重要部分的示例:

<?php
    $postIds = get_post_meta($post->ID, \'postIds\', true); // get custom field value
    $arrayIds = explode(\',\', $postIds); // explode value into an array of ids
    if(count($arrayIds) <= 1) // if array contains one element or less, there\'s spaces after comma\'s, or you only entered one id
    {
        if( strpos($arrayIds[0], \',\') !== false )// if the first array value has commas, there were spaces after ids entered
        {
            $arrayIds = array(); // reset array
            $arrayIds = explode(\', \', $postIds); // explode ids with space after comma\'s
        }

    }

    $args = array(
        \'include\' => $arrayIds // pass array of ids into `include` parameter
    );
    ...
?>

结束