0

Hidden Gems of WordPress – Part 1

For the las two years I’ve started working with WordPress again and re-discovered some hidden gems of WordPress. Here, what I meant by again is that, I wasn’t using WordPress for any kind of web development since 2010 (most probably) and it was because I didn’t have any kind of work related to WordPress and that’s it.

Until Laravel 3.0 was released in February 22, 2012, I was using CodeIgniter and used it for quite a long time to build all the web applications of any size that I’ve worked on back in those days, but anyways. Since Laravel came in my life, rest of the things are history now.

So recently, I mean for the last two years (maybe not very recent tho), I’ve started to develop wordPress plugins for the company (Authlab) where I work and re-discovered the mighty WordPress. Well, it took a decent amount of time to fit in with WordPress again after all these years but I found her much more matured and beautiful than the time I left her. So, in this article, I’m not going to discuss about all the new things that I’ve found in her but some very specific useful functions that most developers probably don’t know or at least forget to use. So let’s begin –

1. wp_list_pluck

$posts = get_posts();

$postTitles = wp_list_pluck($posts, 'post_title');

print_r($postTitles);

// Output:
Array
(
    [0] => Runolfsdottir-Reynolds
    [1] => Luettgen and Hoeger
    [2] => Smith and Kulas
)

This function plucks out the given key/property from an array of array/objects. Also, it accepts a second parameter where the name of the key/property will be the key of the returned associative array. For example:

$posts = get_posts();

$postTitles = wp_list_pluck($posts, 'post_title', 'ID');

print_r($postTitles);

// Output:
Array
(
    10 => Runolfsdottir-Reynolds
    11 => Luettgen and Hoeger
    12 => Smith and Kulas
)

In this case 10, 11 and 12 are the IDs of each post. It reminds me Laravel’s Collection::pluck method btw.

2. wp_list_filter

$posts = get_posts();

$filtered = wp_list_filter($posts, [
    'ID' => 10
]);

print_r($filtered);

// Output:
Array
(
    [0] => WP_Post Object
        (
            [ID] => 10
            [post_author] => 1
            [post_date] => 2019-03-05 21:16:01
            [post_date_gmt] => 0000-00-00 00:00:00
            [post_content] => Hi There!
            // ...
        )

)

This function filters an array of array/objects, based on a set of key => value pairs. In that case, we can provide multiple key => value pair, for example:

$posts = get_posts();

$filtered = wp_list_filter($posts, [
    'post_author' => 1,
    'comment_status' => 'open'
]);

In this case, the result will be an array of posts whose post_author is 1 and comment_status is open. This function also accepts a third argument where we can specify a condition and/or when there’ll be multiple kay => value pairs for filtering. If and is given then all key => value pairs will be matched and by default, it’s and, while or will pull out the posts if any key => value pair matches, for example:

$people = [
    [
        'name' => 'John Doe',
        'occupation' => 'Software Developer'
    ],
    [
        'name' => 'Jane Doe',
        'occupation' => 'Designer'
    ],
    [
        'name' => 'Johnny Doe',
        'occupation' => 'Tester'
    ]
];

$filtered = wp_list_filter($people, [
    'name' => 'Johnny Doe',
    'occupation' => 'Software Developer'
], 'or');

print_r($filtered);

// Output:
Array
(
    [0] => Array
        (
            [name] => John Doe
            [occupation] => Software Developer
        )

    [2] => Array
        (
            [name] => Johnny Doe
            [occupation] => Tester
        )
)

3. wp_list_sort

$posts = get_posts();

$sorted = wp_list_sort($posts, 'post_title');

This function takes an array of array/objects as first argument and sorts them by the key name given as the second argument (order by). By default it sorts the list using ascending (asc) order unless we pass the third argument to tell it how to order, for example:

$posts = get_posts();

$sorted = wp_list_sort($posts, 'post_title', 'desc');

Optionally, we can pass a fourth argument to tell it to preserve the indices/keys, for example:

$people = [
    [
        'name' => 'John Doe',
        'occupation' => 'Software Developer'
    ],
    [
        'name' => 'Jane Doe',
        'occupation' => 'Designer'
    ],
    [
        'name' => 'Johnny Doe',
        'occupation' => 'Tester'
    ]
];

$sorted = wp_list_sort($people, 'occupation', 'desc', true);

print_r($sorted);

// Output:
Array
(
    [2] => Array
    (
        [name] => Johnny Doe
        [occupation] => Tester
    )

    [0] => Array
    (
        [name] => John Doe
        [occupation] => Software Developer
    )

    [1] => Array
    (
        [name] => Jane Doe
        [occupation] => Designer
     )
)

Notice that, the array is ordered by occupation using descending order but the original indices/keys were preserved, the first array item’s key is 2 not 0.

Btw, there is another variation of this function, which is as given below:

$people = [...];

$sorted = wp_list_sort($people, [
    'occupation' => 'asc', // order by occupation using asc
    'name' => 'desc' // order by name using desc
], null, true);

In this case, the second parameter (order by) is an array where an array of multiple order by key => value (order by key => type of order) has been passed instead of a single key name as string. In that case, the third parameter must be null if we want to pass the fourth parameter to preserve the indices.

4wp_parse_list

$list = wp_parse_list('One, Two, Three 4 50');

print_r($list);

// Output:
Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => 4
    [4] => 50
)

This function actually creates an array from a string of comma- or space-separated list of scalar values.

5wp_parse_id_list

$list = wp_parse_id_list([1, 2, '3', '2']);

print_r($list);

// Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

This function takes an array or string of numeric values either in string or integer form and creates an array of integers with completely unique values. The following example creates a unique array of integers from a string of comma- or space-separated list of scalar values:

$list = wp_parse_id_list('1, 2, 3 2 ');

print_r($list);

// Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

6wp_parse_slug_list

$list = wp_parse_slug_list(['slug1', ' slug2', 'slug 1 ', 'slug2']);

print_r($list);

// Output:
Array
(
    [0] => slug1
    [1] => slug2
    [2] => slug-1
)

This function is just like the wp_parse_id_list and the only difference is that, it parses unique slugs (as string) from an array or a string of comma- or space-separated list of scalar values, for example (parsing from string):

$list = wp_parse_slug_list('slug1 slug2, slug 1 slug2');

print_r($list);

// Output:
Array
(
    [0] => slug1
    [1] => slug2
    [2] => slug
    [3] => 1 // also a string
)

7wp_array_slice_assoc

$people = [
    [
        'name' => 'John Doe',
        'email' => 'johndoe@gmail.com',
        'occupation' => 'Software Developer'
    ],
    [
        'name' => 'Jane Doe',
        'email' => 'janedoe@gmail.com',
        'occupation' => 'Designer'
    ],
    [
        'name' => 'Johnny Doe',
        'email' => 'johnnydoe@gmail.com',
        'occupation' => 'Tester'
    ]
];

$slice = [];

foreach ($people as $person) {
    $slice[] = wp_array_slice_assoc($person, ['name', 'email']);
}

print_r($slice);

// Output:
Array
(
    [0] => Array
    (
        [name] => John Doe
        [email] => johndoe@gmail.com
    )

    [1] => Array
    (
        [name] => Jane Doe
        [email] => janedoe@gmail.com
    )

    [2] => Array
    (
        [name] => Johnny Doe
        [email] => johnnydoe@gmail.com
    )
)

This function creates a slice of an associative array. The first argument is the source array, from which we want to create a slice. The second argument is another non-associative array, where it takes one or more key names of the source array to create the slice.

8wp_filter_object_list

$posts = get_posts();

$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
);

print_r($filtered);

// Output:
Array
(
    [0] => Title of Post-1
    [1] => Title of Post-2
)

This function filters an array of objects. The first parameter is the array of objects and in this case an array of posts is given, the second parameter is an associative array of key => value pairs to filter by. The third argument is optional, which tells whether to match all key => value pairs in the object to filter it, we’ve used or to match any key => value, by default it’s and. Finally the fourth optional parameter tells which field to return from the filtered/matched object unless we want the whole object. So for example, we can use it as given below:

$posts = get_posts();

$filtered = wp_filter_object_list(
    $posts,
    ['post_date' => '2019-05-05 03:15:32', 'comment_status' => 'open']
);

In this case, the function will loop through all the posts and it’ll filter out the posts whose post_date is 2019-05-05 03:15:32 and the comment_status is open and finally it’ll return an array of all the matched objects.

9wp_extract_urls

$posts = get_posts();

$urls = wp_extract_urls($posts[0]->post_content);

print_r($urls);

// Output:
Array
(
    [0] => https://wpblog.test/wp-content/uploads/2019/01/Afraz.jpg
    [1] => https://wpblog.test/wp-content/uploads/2019/01/Afreen.jpg
)

The function name itself tells about it’s use case. It simply extracts all the URLs from arbitrary content (not only from a post_content) using RegEx.

10wp_is_numeric_array

if (wp_is_numeric_array(['a', 'b'])) {
    // It's a numeric-indexed array.
}

This function is self descriptive. It simply determines if the variable is a numeric-indexed array. An easy way to distinguish between associative and numeric-indexed array.

That’s all for today, hope it’ll help someone but for more dig into source code. All the functions I’ve mentioned here, are defined in “wp-includes/functions.php” and there are more.


Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]