Array Functions
Array functions help you work with lists of data - like posts, categories, search results, or any collection of items. Instead of manually processing each item, these functions let you filter, transform, count, and organize your data automatically.
Why Array Functions Matter
Raw data challenges:
- Lists like
[post1, post2, post3]that need filtering by status - Category arrays where you only need the names:
"Technology, WordPress, Tips" - Search results that need counting and limiting
- Product lists that need sorting by price or popularity
What array functions solve:
- Smart filtering: Show only published posts from a mixed list
- Data extraction: Get just the category names from complex category objects
- Automatic counting: Display "5 results found" without manual counting
- Dynamic sorting: Arrange products by price, posts by date, or custom criteria
Checking and Counting
Verify what's in your arrays and count items.
count
Essential for showing result counts, checking if arrays have content, and loop limits.
- Description
- Example
- Result
count(array_or_string)
When to use:
- Display search result counts
- Check if arrays have content before showing
- Set loop limits and pagination
// Count search results for display
count(search_results)
// Check number of post categories
count(wp.post.categories)
// String length checking
count(post_title)
// [result1, result2, result3] → show count
3
// [category1, category2] → number of categories
2
// "WordPress Tips" → character count
14
includes
Perfect for checking permissions, validating selections, and conditional logic.
- Description
- Example
- Result
includes(value_to_find, array_to_search)
When to use:
- Check user permissions and roles
- Validate form selections
- Filter content based on categories or tags
// Check if user has admin role
includes('administrator', user_roles)
// Validate selected category
includes(selected_category, allowed_categories)
// Check post status
includes(post_status, ['publish', 'future', 'private'])
// ['subscriber', 'administrator'] → has admin access
true
// ['technology', 'wordpress'] → valid selection
true
// 'publish' in allowed statuses → is public
true
isset
Verify that object properties exist before trying to use them.
- Description
- Example
- Result
isset(object_or_array, property_name)
When to use:
- Check if custom fields exist
- Validate object structure
- Prevent errors when accessing properties
// Check if post has featured image
isset(wp.post, 'featured_image')
// Verify custom field exists
isset(post_meta, 'custom_price')
// Check user profile completeness
isset(user_profile, 'bio')
// Post object has featured_image property
true
// Custom field 'custom_price' exists
false
// User has bio field filled
true
Finding and Filtering
Extract specific items or properties from your arrays.
filter
Remove unwanted items based on conditions, like showing only published posts.
- Description
- Example
- Result
filter(array, (item) -> condition)
When to use:
- Show only published posts
- Filter products by price range
- Display posts from specific categories
// Show only published posts
filter(all_posts, (post) -> post.post_status == 'publish')
// Products under $50
filter(products, (product) -> product.price < 50)
// Posts with featured images
filter(posts, (post) -> post.featured_image != null)
// Only posts with status 'publish'
[{title: "Live Post", status: "publish"}]
// Only affordable products
[{name: "Widget", price: 29.99}]
// Only posts that have images
[{title: "Visual Post", featured_image: "image.jpg"}]
findIndex
Locate where a specific item appears in an array.
- Description
- Example
- Result
findIndex(array, (item) -> condition)
When to use:
- Find current page in pagination
- Locate specific user in list
- Check position of featured content
// Find admin user position
findIndex(users, (user) -> user.role == 'administrator')
// Locate current page
findIndex(pages, (page) -> page.id == current_page_id)
// Find featured product
findIndex(products, (product) -> product.featured == true)
// Admin user found at position 2
2
// Current page is at position 0 (first)
0
// No featured product found
-1
pluck
Get just one property from each object in an array, like extracting all product names.
- Description
- Example
- Result
pluck(array_of_objects, property_name)
When to use:
- Get list of category names
- Extract all product prices
- Create lists of titles or IDs
// Extract all category names
pluck(post_categories, 'name')
// Get all product prices
pluck(products, 'price')
// List all user emails
pluck(users, 'email')
// ['Technology', 'WordPress', 'Tips']
['Technology', 'WordPress', 'Tips']
// [19.99, 29.99, 39.99]
[19.99, 29.99, 39.99]
// ['[email protected]', '[email protected]']
['[email protected]', '[email protected]']
Transforming Items
Change or reorganize items in your arrays.
foreach
Apply changes to every item in an array, like adding calculated fields.
- Description
- Example
- Result
foreach(array, (item) -> new_value)
When to use:
- Add calculated fields to objects
- Format data for display
- Combine multiple properties
// Add total cost to products
foreach(products, (product) -> merge(product, {
'total': product.price * product.quantity
}))
// Format user display names
foreach(users, (user) -> user.first_name ~ ' ' ~ user.last_name)
// Add URL slugs to categories
foreach(categories, (cat) -> merge(cat, {
'url': '/category/' ~ cat.slug
}))
// Products with calculated totals
[{name: "Widget", price: 19.99, quantity: 2, total: 39.98}]
// Formatted full names
["John Smith", "Jane Doe"]
// Categories with full URLs
[{name: "Tech", slug: "tech", url: "/category/tech"}]
sort
Put array items in alphabetical or numerical order.
- Description
- Example
- Result
sort(array) // A to Z, low to high
rsort(array) // Z to A, high to low
When to use:
- Alphabetize category lists
- Sort prices low to high
- Organize content chronologically
// Alphabetize category names
sort(['WordPress', 'Design', 'Technology'])
// Sort prices high to low
rsort([19.99, 39.99, 29.99])
// Organize years chronologically
sort([2023, 2021, 2024, 2022])
// Alphabetical order
['Design', 'Technology', 'WordPress']
// Highest prices first
[39.99, 29.99, 19.99]
// Chronological order
[2021, 2022, 2023, 2024]
usort
Sort using your own rules, like by price, date, or custom criteria.
- Description
- Example
- Result
usort(array, (a, b) -> comparison)
Comparison rules:
- Return negative number:
acomes beforeb - Return positive number:
bcomes beforea - Return zero:
aandbare equal
When to use:
- Sort products by price
- Order posts by date
- Rank items by custom scores
// Sort products by price (low to high)
usort(products, (a, b) -> a.price - b.price)
// Sort posts by date (newest first)
usort(posts, (a, b) -> b.date - a.date)
// Sort by name length (shortest first)
usort(names, (a, b) -> count(a) - count(b))
// Cheapest products first
[{name: "Basic", price: 9.99}, {name: "Pro", price: 29.99}]
// Newest posts first
[{title: "Latest", date: "2024-01-15"}, {title: "Older", date: "2024-01-10"}]
// Shortest names first
["Jo", "Jane", "Robert"]
Combining and Splitting
Join arrays into text or split text into arrays.
join
Convert arrays into readable, formatted strings.
- Description
- Example
- Result
join(array, separator)
When to use:
- Display category lists
- Create comma-separated values
- Build navigation breadcrumbs
// Display post categories
join(['WordPress', 'Design', 'Tips'], ', ')
// Create breadcrumb navigation
join(['Home', 'Blog', 'WordPress'], ' > ')
// Build tag list
join(['php', 'javascript', 'css'], ' | ')
// Readable category list
"WordPress, Design, Tips"
// Navigation path
"Home > Blog > WordPress"
// Tag separator
"php | javascript | css"
split
Convert formatted strings into arrays for processing.
- Description
- Example
- Result
split(text, separator)
When to use:
- Process comma-separated values
- Parse user input
- Break apart formatted strings
// Process tag input
split('wordpress, design, tips', ', ')
// Parse name parts
split('John Smith', ' ')
// Break apart URL path
split('/blog/wordpress/tips', '/')
// Individual tags for processing
['wordpress', 'design', 'tips']
// Separate name components
['John', 'Smith']
// URL path segments
['', 'blog', 'wordpress', 'tips']
merge
Merge multiple objects together, useful for adding properties or combining data.
- Description
- Example
- Result
merge(object1, object2, ...)
When to use:
- Add calculated fields to data
- Combine user profile information
- Merge configuration settings
// Add calculated fields to product
merge(product_data, {'total_cost': price * quantity})
// Combine user information
merge(basic_profile, contact_info, preferences)
// Add display properties
merge(post_data, {'formatted_date': date('F j, Y', post_date)})
// Product with calculated field
{name: "Widget", price: 19.99, quantity: 2, total_cost: 39.98}
// Complete user profile
{name: "John", email: "[email protected]", theme: "dark"}
// Post with formatted date
{title: "My Post", post_date: "2024-01-15", formatted_date: "January 15, 2024"}
Adding and Removing Items
Modify arrays by adding or removing specific items.
push / unshift
Add new items to arrays in specific positions (begining/end).
- Description
- Example
- Result
push(array, new_item) // Add to end
unshift(array, new_item) // Add to beginning
When to use:
- Add items to navigation menus
- Insert default options in lists
- Append additional data
// Add "Other" option to end of categories
push(category_options, 'Other')
// Add "All" option to beginning of filters
unshift(filter_options, 'All')
// Append current page to breadcrumbs
push(breadcrumb_links, current_page_title)
// Category list with "Other" at end
['Technology', 'Design', 'Other']
// Filters with "All" at beginning
['All', 'Published', 'Draft', 'Private']
// Complete breadcrumb path
['Home', 'Blog', 'Current Page']
set / unset
Modify or remove specific items using their position or property path.
- Description
- Example
- Result
set(array, path, new_value) // Change item
unset(array, path) // Remove item
Path formats:
- Array index:
"[0]","[1]" - Object property:
"[0].price","user.name"
When to use:
- Update specific product prices
- Remove sensitive data fields
- Modify nested object properties
// Update first product price
set(products, '[0].price', 24.99)
// Remove user password field
unset(user_data, 'password')
// Change specific category name
set(categories, '[1].name', 'Web Development')
// Product with updated price
[{name: "Widget", price: 24.99}, {name: "Gadget", price: 39.99}]
// User data without password
{name: "John", email: "[email protected]", role: "admin"}
// Categories with updated name
[{name: "Technology"}, {name: "Web Development"}]
Working with Object Properties
Extract keys and values from objects for display or processing.
joinKeys / joinValues
Extract either the property names or values from objects.
- Description
- Example
- Result
joinKeys(object, separator) // Get property names
joinValues(object, separator) // Get property values
When to use:
- Create lists of available options
- Display all values from settings
- Generate form field lists
// List available post types
joinKeys(post_type_options, ', ')
// Show all prices from price list
joinValues(pricing_options, ' | ')
// Display form field names
joinKeys(user_form_fields, ', ')
// Available content types
"post, page, product, event"
// All pricing options
"$9.99 | $19.99 | $29.99"
// Form field list
"name, email, phone, message"