Now easier than ever to use wp_query and sort posts using values from a field in Simple Fields

Today version 1.3.3 of Simple Fields is out. The full changelog is available at WordPress.org.

This update features a new and simplified way to sort posts using wp_query.

When using wp_query to fetch posts sorted by meta values you usually do something like this:

$args = array(
	"orderby" => "meta_value",
	"meta_key" => "my_custom_field_key",
	"order" => "asc"
);
$my_query = new WP_Query($args);

Then if you wanted to sort posts by a value that was stored by Simple Fields then you had to find out what the meta key for the field was and then use that in the query like this:

$args = array(
	"orderby" => "meta_value",
	"meta_key" => "_simple_fields_fieldGroupID_2_fieldID_0_numInSet_0",
	"order" => "asc"
);
$my_query = new WP_Query($args);

Pretty much the same, but a bit more difficult since you have to get the meta key and then you have to keep in mind that the meta key can change if you have a dev, stage and production server.

Here’s where the latest update come into play. Since we know the slugs for the field group and the field (we kinda entered them ourself in the GUI or using code, didn’t we?) we can use those slugs instead:

$args = array(
	"orderby" => "meta_value",
	"sf_meta_key" => "my_field_group_slug/my_field_slug",
	"order" => "asc"
);
$my_query = new WP_Query($args);

And boom! Simple Fields automatically gets the correct custom fields key and places that in the “meta_key” argument. No more worries about changing field ids between development and productions servers.

Altough it works great, you have yo remember that different field types store their values in different ways. it works really good for plain text, date/timepicker, and probably some more too, but there are field types that store their values as serialized objects and so on.

Oh, this update also adds the method get_field_by_fieldgroup_and_slug_string() that you can use yourself in your code if you for any reason want to get information about a field based on the slugs of the field and the field group is belongs to.

global $sf;
$field_array = $sf->get_field_by_fieldgroup_and_slug_string("my_fieldgroup_slug/my_field_slug");
echo "Here is some info about the field:";
print_r($field_array);

3 thoughts on “Now easier than ever to use wp_query and sort posts using values from a field in Simple Fields

  1. AL

    This is great, but can it also be used to GET posts with a certain Simple Fields value? Like:

    get_posts(array(‘meta_query’ => array(‘sf_key’ => ‘some-key’, ‘value’ => ‘some value’)))

    And also – what if the Simple Field is an array of values (like if you’re using a Taxonomy Term as the Simple Field), how can I grab posts that have a certain term selected?

Leave a Reply