arraypress / wp-object-utils
Find a post, term or user by whatever you were handed: an id, a slug, a name, an email or the object itself.
Requires
- php: >=8.3
Requires (Dev)
- phpcompatibility/phpcompatibility-wp: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^3.13.5
- wp-coding-standards/wpcs: ^3.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Find a post, term or user by whatever you were handed: an id, a slug, a name, an email, or the object itself.
What it does
Core has a different function per field — get_page_by_path(),
get_term_by(), get_user_by() — so before you can look something up you
have to work out what you are holding. Code that accepts input from a
shortcode, a REST request or a CSV import ends up doing that by hand, usually
with a chain of is_numeric() checks.
This takes any of them and gives you the object back, or null.
Features
- Resolve a post, term or user from an id, slug, name, title or email
- Pass the object itself and get it straight back, so callers need no special case
- Turn a list of mixed identifiers into objects in one call
- Ask only for the id, when that is all you need
- Check something exists without loading it
- Search by a partial string, ready for a select or an autocomplete
Installation
composer require arraypress/wp-object-utils
Quick start
A shortcode that takes whatever the author typed:
use ArrayPress\ObjectUtils\Posts; add_shortcode( 'product_price', function ( $atts ) { // 'id', 'my-product-slug' or 'My Product' all work. $product = Posts::find( $atts['product'] ?? 0, 'product' ); if ( ! $product ) { return ''; } return esc_html( get_post_meta( $product->ID, '_price', true ) ); } );
Users::find() takes just the identifier — id, login, email, slug or the
WP_User itself. Terms::find() takes the taxonomy as its second argument,
since a slug is only unique within one.
Requirements
- PHP 8.3 or later
- WordPress 7.1 or later
License
GPL-2.0-or-later