如何使用GET_POST()仅返回某些字段

时间:2013-07-30 作者:Wern Ancheta

我正在尝试使用get_posts() WordPress中的函数。我目前有以下代码:

    $posts_args = array(
        \'orderby\' => \'post_date\',
        \'order\' => \'DESC\',
        \'post_type\' => \'post\',
        \'post_status\' => \'publish\',
        \'posts_per_page\' => 5,
        \'fields\' => \'ids\'
    );

    $post_ids_r = get_posts($posts_args);
如果我只想获得id,这很好。但是如果我想获得永久链接或文章标题以及id,我不知道该怎么做。我已经尝试了以下方法:

\'fields\' => array(\'ids\', \'post_titles\')
\'fields\' => \'ids,post_titles\'
\'fields\' => \'ids,titles\'
\'fields\' => array(\'ids\',\'titles\')
但什么都不管用,我想它唯一能识别的是ids 领域如果真的无法使用get_posts()? 提前谢谢。

6 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

get_posts passes the heavy lifting off to WP_Query 如果你看看这个类的来源,你会发现只有limited number of options with that fields argument. 这方面只有三种选择switch-- ids, id=>parent, 默认情况下,一切。

您可以使用posts_fields 但是,可以通过过滤器更改返回的字段it looks like you need to pass \'suppress_filters => false in the arguments in order to get that filter to run. 应该是这样的:

function alter_fields_wpse_108288($fields) {
  return \'ID,post_title\'; // etc
}
add_filter(\'posts_fields\',\'alter_fields_wpse_10888\');
然而,还有一个更大的问题。返回的post对象是通过调用get_postit doesn\'t honor the values passed into the original query 我也没有办法改变get_posts 或在WP_Post class itself.

SO网友:gmazzap

看看这个

function get_posts_fields( $args = array() ) {
  $valid_fields = array(
    \'ID\'=>\'%d\', \'post_author\'=>\'%d\',
    \'post_type\'=>\'%s\', \'post_mime_type\'=>\'%s\',
    \'post_title\'=>false, \'post_name\'=>\'%s\', 
    \'post_date\'=>\'%s\', \'post_modified\'=>\'%s\',
    \'menu_order\'=>\'%d\', \'post_parent\'=>\'%d\', 
    \'post_excerpt\'=>false, \'post_content\'=>false,
    \'post_status\'=>\'%s\', \'comment_status\'=>false, \'ping_status\'=>false,
    \'to_ping\'=>false, \'pinged\'=>false, \'comment_count\'=>\'%d\'
  );
  $defaults = array(
    \'post_type\' => \'post\',
    \'post_status\' => \'publish\',
    \'orderby\' => \'post_date\',
    \'order\' => \'DESC\',
    \'posts_per_page\' => get_option(\'posts_per_page\'),
  );
  global $wpdb;
  $args = wp_parse_args($args, $defaults);
  $where = "";
  foreach ( $valid_fields as $field => $can_query ) {
    if ( isset($args[$field]) && $can_query ) {
      if ( $where != "" )  $where .= " AND ";
      $where .= $wpdb->prepare( $field . " = " . $can_query, $args[$field] );
    }
  }
  if ( isset($args[\'search\']) && is_string($args[\'search\']) ) {
      if ( $where != "" )  $where .= " AND ";
      $where .= $wpdb->prepare("post_title LIKE %s", "%" . $args[\'search\'] . "%");
  }
  if ( isset($args[\'include\']) ) {
     if ( is_string($args[\'include\']) ) $args[\'include\'] = explode(\',\', $args[\'include\']); 
     if ( is_array($args[\'include\']) ) {
      $args[\'include\'] = array_map(\'intval\', $args[\'include\']); 
      if ( $where != "" )  $where .= " OR ";
      $where .= "ID IN (" . implode(\',\', $args[\'include\'] ). ")";
    }
  }
  if ( isset($args[\'exclude\']) ) {
     if ( is_string($args[\'exclude\']) ) $args[\'exclude\'] = explode(\',\', $args[\'exclude\']); 
     if ( is_array($args[\'exclude\']) ) {
      $args[\'exclude\'] = array_map(\'intval\', $args[\'exclude\']);
      if ( $where != "" ) $where .= " AND "; 
      $where .= "ID NOT IN (" . implode(\',\', $args[\'exclude\'] ). ")";
    }
  }
  extract($args);
  $iscol = false;
  if ( isset($fields) ) { 
    if ( is_string($fields) ) $fields = explode(\',\', $fields);
    if ( is_array($fields) ) {
      $fields = array_intersect($fields, array_keys($valid_fields)); 
      if( count($fields) == 1 ) $iscol = true;
      $fields = implode(\',\', $fields);
    }
  }
  if ( empty($fields) ) $fields = \'*\';
  if ( ! in_array($orderby, $valid_fields) ) $orderby = \'post_date\';
  if ( ! in_array( strtoupper($order), array(\'ASC\',\'DESC\')) ) $order = \'DESC\';
  if ( ! intval($posts_per_page) && $posts_per_page != -1)
     $posts_per_page = $defaults[\'posts_per_page\'];
  if ( $where == "" ) $where = "1";
  $q = "SELECT $fields FROM $wpdb->posts WHERE " . $where;
  $q .= " ORDER BY $orderby $order";
  if ( $posts_per_page != -1) $q .= " LIMIT $posts_per_page";
  return $iscol ? $wpdb->get_col($q) : $wpdb->get_results($q);
}
这是一个模仿get\\U帖子的函数,但它能够获得您想要的字段。请注意:此功能是not get\\u posts有两个很大的限制:只在posts表中运行,所以分类法和元查询不能运行!

但是,查询可以依赖于所有post字段和一些“特殊”参数,如include, excludesearch.

好的方面是:您可以检索的字段是all post表的字段。只需在fields 论点好处:只传递一个字段将返回一个一维字符串或整数数组(而不是对象数组)。

可用参数列表包括:

$available_args = array(
  \'ID\', // int
  \'post_author\', // string
  \'post_type\', // string
  \'post_mime_type\', // string
  \'post_name\', // string
  \'post_date\', // string
  \'post_modified\', // string
  \'menu_order\', // int
  \'post_parent\', // int 
  \'post_status\', // string
  \'comment_status\', // string
  \'comment_count\', // int 
  \'orderby\', // string, a valid field name
  \'order\', // string \'ASC\', or \'DESC\',
  \'posts_per_page\', // int
  \'include\', // array (or comma separed string) of post ids
  \'exclude\', // array (or comma separed string) of post ids
  \'search\', // string if passed will search for it in post title
  \'fields\', // array (or comma separed string) of fields to retrieve.
            // If only 1 field is passed a \'flat\' array is returned 
);
用法示例
// Retrieve the date and the title of pages having \'Hello\' in the title
$pages_hello = get_posts_fields("post_type=page&search=Hello&fields=post_date,post_title");


// another example
$args = array(
  \'post_type\' => \'custom_post\',
  \'posts_per_page\' => -1,
  \'post_parent\' => 1,
  \'include\' => array(2,3,4),
  \'exclude\' => \'6,8,10\',
  \'fields\' => array(\'post_title\', \'comment_status\')
);
get_posts_fields($args);


// One more, just for fun ;)
$args = array(
  \'post_type\' => \'attachment\', \'posts_per_page\' => -1,
  \'post_status\' => \'inherit\', \'fields\' => \'post_mime_type\'
);
foreach ( array_count_values ( get_posts_fields($args) ) as $mime => $count ) {
  echo "I have $count media of the type $mime" . PHP_EOL;
}

SO网友:Rens Tillmann

您只能使用\'ids\'\'id=>parent\' 对于参数fields.

如果您分析其他内容,它将返回所有字段(这是默认值)。

但是,如果Wordpress可以添加以下两个选项,那就太好了:\'titles\'\'ids_and_titles\'.

我不知道如何解析此参数的数组。我也认为这永远不会发生,因为通用汽车给出的答案是有限的。

更多信息:http://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter

SO网友:Vanillabacke

感谢gmazzap提供该功能!我正在寻找一种解决方案,以便在get\\U POST中获得一些自定义字段,所以我可以自由地将其扩展到Posteta表的自定义字段:

function get_posts_fields($args = array())
{
    $valid_fields = array(
        \'ID\' => \'%d\',
        \'post_author\' => \'%d\',
        \'post_type\' => \'%s\',
        \'post_mime_type\' => \'%s\',
        \'post_title\' => false,
        \'post_name\' => \'%s\',
        \'post_date\' => \'%s\',
        \'post_modified\' => \'%s\',
        \'menu_order\' => \'%d\',
        \'post_parent\' => \'%d\',
        \'post_excerpt\' => false,
        \'post_content\' => false,
        \'post_status\' => \'%s\',
        \'comment_status\' => false,
        \'ping_status\' => false,
        \'to_ping\' => false,
        \'pinged\' => false,
        \'comment_count\' => \'%d\',
        \'custom_fields\' => false,
    );

    $defaults = array(
        \'post_type\' => \'post\',
        \'post_status\' => \'publish\',
        \'orderby\' => \'post_date\',
        \'order\' => \'DESC\',
        \'posts_per_page\' => get_option(\'posts_per_page\')
    );

    global $wpdb;

    $args = wp_parse_args($args, $defaults);
    $where = "";
    $meta = "";
    $groupBy = "";

    foreach ($valid_fields as $field => $can_query) {
        if (isset($args[$field]) && $can_query) {
            if ($where != "") {
                $where .= " AND ";
            }
            $where .= $wpdb->prepare(
                $wpdb->posts.".".$field . " = " . $can_query,
                $args[$field]
            );
        }
    }

    if (isset($args[\'search\']) && is_string($args[\'search\'])) {
        if ($where != "") {
            $where .= " AND ";
        }
        $where .= $wpdb->prepare(
            "post_title LIKE %s",
            "%" . $args[\'search\'] . "%"
        );
    }

    if (isset($args[\'include\'])) {
        if (is_string($args[\'include\'])) {
            $args[\'include\'] = explode(\',\', $args[\'include\']);
        }
        if (is_array($args[\'include\'])) {
            $args[\'include\'] = array_map(\'intval\', $args[\'include\']);
            if ($where != "") {
                $where .= " OR ";
            }
            $where .= $wpdb->posts.".ID IN (" . implode(\',\', $args[\'include\']) . ")";
        }
    }

    if (isset($args[\'exclude\'])) {
        if (is_string($args[\'exclude\'])) {
            $args[\'exclude\'] = explode(\',\', $args[\'exclude\']);
        }
        if (is_array($args[\'exclude\'])) {
            $args[\'exclude\'] = array_map(\'intval\', $args[\'exclude\']);
            if ($where != "") {
                $where .= " AND ";
            }
            $where .= $wpdb->posts.".ID NOT IN (" . implode(\',\', $args[\'exclude\']) . ")";
        }
    }




    extract($args);
    $iscol = false;
    if (isset($fields)) {
        if (is_string($fields)) {
            $fields = explode(\',\', $fields);
        }
        if (is_array($fields)) {
            $fields = array_intersect($fields, array_keys($valid_fields));
            if (count($fields) == 1) {
                $iscol = true;
            }

            for($i = 0; $i < count($fields); $i++) {
              $fields[$i] = "$wpdb->posts.$fields[$i]";
            }

        }
    }

    if (isset($args[\'custom_fields\'])) {
      if (is_string($args[\'custom_fields\'])) {
            $args[\'custom_fields\'] = explode(\',\', $args[\'custom_fields\']);
      }


      if (is_array($args[\'custom_fields\'])) {
          foreach( $args[\'custom_fields\'] as $custom_field) {
            $fields[] =  "MAX(CASE WHEN df_postmeta.meta_key = \'$custom_field\' then df_postmeta.meta_value ELSE NULL END) as $custom_field";
          }
          $meta = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->postmeta.post_id = $wpdb->posts.ID)";
          $groupBy = " GROUP BY $wpdb->posts.ID, $wpdb->posts.post_title";
        }
    }

    if (empty($fields)) {
        $fields = \'*\';
    } else {
      $fields = implode(\',\', $fields);
    }



    if( in_array($orderby, $valid_fields) ) {
      $orderby = $wpdb->posts.\'.\'.$orderby;
    }else if( isset( $args[\'custom_fields\']) && in_array($orderby, $args[\'custom_fields\']) ) {
      $orderby = $orderby;
    } else {
      $orderby = $wpdb->posts.\'.post_date\';
    }


    if (!in_array(strtoupper($order), array(\'ASC\', \'DESC\'))) {
        $order = \'DESC\';
    }

    if (!intval($posts_per_page) && $posts_per_page != -1) {
        $posts_per_page = $defaults[\'posts_per_page\'];
    }

    if ($where == "") {
        $where = "1";
    }



    $q = "SELECT $fields FROM $wpdb->posts " . $meta . " WHERE " . $where;
    $q .= $groupBy;
    $q .= " ORDER BY $orderby $order";

    if ($posts_per_page != -1) {
        $q .= " LIMIT $posts_per_page";
    }

    print $q;

    return $iscol ? $wpdb->get_col($q) : $wpdb->get_results($q);
}
您也可以使用该字段的orderby。一个小例子:

$args = array(
    \'post_type\' => \'projects\',
    \'posts_per_page\' => -1,
    \'fields\' => array(\'ID\', \'post_title\'),
    \'orderby\' => \'project_clients\',
    \'order\' => \'DESC\',

    \'custom_fields\' => array(
        \'project_clients\',
        \'project_dop\'
     ),
);
$projects = get_posts_fields($args);

SO网友:lukeocom

有趣的是,您可以使用WP Rest API使用\\u fields参数来实现这一点

https://yoursite.com/wp-json/wp/v2/posts?_fields=author,id,excerpt,title,link
有关API的更多信息,请单击此处:https://developer.wordpress.org/rest-api/

SO网友:Craig Grella

如果要在模板或插件中显示帖子标题,可以使用:

get_the_title($ID)
参见wordpress参考:http://codex.wordpress.org/Function_Reference/get_the_title

如果在循环外使用,则需要$ID。无论哪种方式,都可能会这样使用:

您还可以使用:

\\u permalink()-检索帖子permalink the\\u title()-检索帖子标题

这些都是wordpress模板标签。您可以使用的模板标记的完整列表如下所示:http://codex.wordpress.org/Template_Tags

结束

相关推荐