Skip to content

Instantly share code, notes, and snippets.

@richaber
Last active July 13, 2022 20:12
Show Gist options
  • Save richaber/f92aca3bd56fffd7f2630891d6fa5724 to your computer and use it in GitHub Desktop.
Save richaber/f92aca3bd56fffd7f2630891d6fa5724 to your computer and use it in GitHub Desktop.
WP List Utils wp_list_pluck wp_list_filter wp_list_sort wp_parse_list wp_parse_id_list wp_parse_slug_list wp_array_slice_assoc wp_filter_object_list wp_extract_urls
<?php
$people = [
[
'name' => 'John Doe',
'email' => '[email protected]',
'occupation' => 'Software Developer',
],
[
'name' => 'Jane Doe',
'email' => '[email protected]',
'occupation' => 'Designer',
],
[
'name' => 'Johnny Doe',
'email' => '[email protected]',
'occupation' => 'Tester',
],
];
$posts = get_posts();
$post_titles = wp_list_pluck( $posts, 'post_title' );
$post_titles = wp_list_pluck( $posts, 'post_title', 'ID' );
$filtered = wp_list_filter( $posts, [
'ID' => 10,
] );
$filtered = wp_list_filter( $posts, [
'post_author' => 1,
'comment_status' => 'open',
] );
$filtered = wp_list_filter( $people, [
'name' => 'Johnny Doe',
'occupation' => 'Software Developer'
], 'or' );
$sorted = wp_list_sort( $posts, 'post_title' );
$sorted = wp_list_sort( $posts, 'post_title', 'desc' );
$sorted = wp_list_sort( $people, 'occupation', 'desc', true );
$sorted = wp_list_sort( $people, [
'occupation' => 'asc', // order by occupation using asc
'name' => 'desc' // order by name using desc
], null, true );
$list = wp_parse_list( 'One, Two, Three 4 50' );
$list = wp_parse_id_list( [ 1, 2, '3', '2' ] );
$list = wp_parse_id_list( '1, 2, 3 2 ' );
$list = wp_parse_slug_list( [ 'slug1', ' slug2', 'slug 1 ', 'slug2' ] );
$list = wp_parse_slug_list( 'slug1 slug2, slug 1 slug2' );
$slice = [];
foreach ( $people as $person ) {
$slice[] = wp_array_slice_assoc( $person, [ 'name', 'email' ] );
}
$filtered = wp_filter_object_list(
$posts,
[ 'post_date' => '2019-05-05 03:15:32', 'comment_status' => 'open' ],
'or', // match any field
'post_title' // only return post_title
);
$filtered = wp_filter_object_list(
$posts,
[ 'post_date' => '2019-05-05 03:15:32', 'comment_status' => 'open' ]
);
$urls = wp_extract_urls( $posts[0]->post_content );
if ( wp_is_numeric_array( [ 'a', 'b' ] ) ) {
// It's a numeric-indexed array.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment