Skip to content

Instantly share code, notes, and snippets.

@itsmereal
Created February 19, 2025 20:48
Show Gist options
  • Save itsmereal/e71a9fa104368db4fd80e645d120693f to your computer and use it in GitHub Desktop.
Save itsmereal/e71a9fa104368db4fd80e645d120693f to your computer and use it in GitHub Desktop.
Customize wp_dropdown_pages() Option Labels

Customize wp_dropdown_pages() Option Labels

This WordPress snippet modifies the default output of wp_dropdown_pages() to display page options in the format:

{Page Title} - {slug} ({ID})

Instead of the default page title, each option in the dropdown will now include the page’s slug and ID for better clarity. This is useful for administrators working with multiple pages that might have similar titles.

Usage:

Simply add this snippet to your theme’s functions.php or a custom plugin, and it will automatically apply to all wp_dropdown_pages() calls on your site.

Example Output:

<option value="1">Home - home (1)</option>
<option value="2">About Us - about-us (2)</option>
<option value="3">Contact - contact (3)</option>

I hope it helps with those frustrating dropdown fields with identical labels!

<?php
function modify_wp_dropdown_pages_output($output) {
if (empty($output)) {
return $output;
}
// Use regex to find option elements
$output = preg_replace_callback('/<option (.*?)value="(\d+)"(.*?)>(.*?)<\/option>/', function ($matches) {
$page_id = $matches[2];
$page = get_post($page_id);
if ($page) {
// Format the option text as "{Page Title} - {slug} ({ID})"
$new_label = "{$page->post_title} - {$page->post_name} ({$page->ID})";
return "<option {$matches[1]}value=\"{$page_id}\"{$matches[3]}>{$new_label}</option>";
}
return $matches[0]; // Return unchanged if page not found
}, $output);
return $output;
}
add_filter('wp_dropdown_pages', 'modify_wp_dropdown_pages_output');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment