Skip to content

Instantly share code, notes, and snippets.

@mhull
Last active June 3, 2016 00:25
Show Gist options
  • Save mhull/4b4a8f5eb6b67fc429111526a451f711 to your computer and use it in GitHub Desktop.
Save mhull/4b4a8f5eb6b67fc429111526a451f711 to your computer and use it in GitHub Desktop.
<?php
/**
* The `get_by` method allows us to get extended post objects by field value.
*
* The method expects the input array to be identical to that for `WP_Query`, and it also allows two optional custom arguments,
* `fields` and `fields_relation` to skirt around the `$meta_query` argument
*/
$people_named_michael = Helping_Friendly_Post::get_by( array(
'post_type' => 'person',
'fields' => array(
'first_name' => 'Michael'
)
));
<?php
/**
* The `Helping_Friendly_Post` class is an exercise in thinking about extending the `WP_Post` class
*
* @see https://github.com/mhull/helping-friendly-plugin/blob/master/lib/class-hphp-post.php
*/
/**
* To get a new extended post by ID
*/
$extended_post = new Helping_Friendly_Post( $post_id );
# now we have all the post meta in the `$extended_post->fields` array
$wow = $extended_post->fields['my_meta_key'];
# ...as well as the `WP_Post` object itself (the original post we have extended)
$awesome = $extended_post->post->post_status;
/**
* If we already have the full `WP_Post` and not just the ID, we can save a trip
* to the database (or the cache I suppose)
*/
global $post;
$extended_post = new Helping_Friendly_Post( $post );
$super_easy_field_value = $extended_post->fields['my_meta_key']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment