wp_basename( string $path, string $suffix = '' ): string
- Since
- 3.1.0
- Source
wp-includes/formatting.php:5683
Extracts the filename portion of a path or URL by wrapping PHP's basename() with URL-encoding so multibyte UTF-8 filenames survive intact. The optional $suffix trims an exact, case-sensitive trailing string such as a file extension. It does not sanitize or validate the result, so pair it with sanitize_file_name() before writing anything to disk.
Compatibility
- WordPress
- since 3.1.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$pathstring- A path.
$suffixstringoptional- If the filename ends in suffix this will also be cut off.Default:
''
Return value
string- The base name of the given path.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Get the filename from a full file system path
A plugin building a download link needs just the filename, not the full server path to a theme asset.
$path = get_stylesheet_directory() . '/style.css';
$filename = wp_basename( $path );
echo esc_html( $filename );Strip a known extension from an uploaded filename
Code that needs the bare name of an image file, without its extension, to use as a slug or label.
$uploaded_path = '/var/www/html/wp-content/uploads/2024/01/vacation-photo.jpg';
$name_without_extension = wp_basename( $uploaded_path, '.jpg' );
echo esc_html( $name_without_extension );The suffix match is case-sensitive, so '.JPG' would not be stripped by this call.
Common problems and fixes · 4
- Why does plain basename() mangle a filename with accented or non-Latin characters, and does wp_basename fix that?
- Why did wp_basename split my filename on a slash-like sequence that wasn't a real path separator?
- Does the $suffix parameter strip any extension automatically, like pathinfo() can?
- Can I hand wp_basename a full URL with a query string?
Why does plain basename() mangle a filename with accented or non-Latin characters, and does wp_basename fix that?
Why did wp_basename split my filename on a slash-like sequence that wasn't a real path separator?
Does the $suffix parameter strip any extension automatically, like pathinfo() can?
Can I hand wp_basename a full URL with a query string?
Alternatives and related functions
basename- When the path is guaranteed to be plain ASCII and you don't need the UTF-8 safe encode/decode round trip.
pathinfo- When you need the extension, directory name, or filename without extension broken out separately, rather than just the base filename.
sanitize_file_name- When you're about to write the filename to disk or a database and need it stripped of unsafe or disallowed characters.
wp_check_filetype- When you need to determine or validate the file's MIME type rather than just extract its name.
Performance profile
How much work a call to wp_basename() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 15
- Plugin surface
- None
- Called by
- 50
Touches nothing outside its own arguments.
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5. The body compiles to 15.
Nothing here hands control to plugin code.
50 places in core call this, so the cost is paid more often than your own code shows.
What one call costs · 1 distinct outcome
One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_basename() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 15 | urlencode(), basename(), urldecode() |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 15 | 15 | 0 | |
| 8.5 | 15 | 15 | 0 | |
| 8.4 | 15 | 15 | 0 | 3 fewer instructions than PHP 8.3 |
| 8.3 | 18 | 18 | 0 | |
| 8.2 | 18 | 18 | 0 | |
| 8.1 | 18 | 18 | 0 | |
| 7.4 | 18 | 18 | 0 |
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Used by · 50
- Custom_Background::handle_upload()Handles an Image upload for the background image.
- Custom_Image_Header::create_attachment_object()Creates an attachment 'object'.
- Custom_Image_Header::step_2()Displays second step of custom header image page.
- Custom_Image_Header::step_2_manage_upload()Uploads the file to be cropped in the second step.
- Custom_Image_Header::step_3()Displays third step of custom header image page.
- WP_Customize_Manager::get_return_url()Gets URL to link the user to when closing the Customizer.
- WP_Customize_Manager::import_theme_starter_content()Imports theme starter content into the customized state.
- WP_Customize_Manager::prepare_starter_content_attachments()Prepares starter content attachments.
- WP_Customize_Media_Control::to_json()Refresh the parameters passed to the JavaScript via JSON.
- WP_Image_Editor::generate_filename()Builds an output filename based on current file, and adding proper suffix
- WP_Image_Editor::get_output_format()Returns preferred mime-type and extension based on provided file's extension and mime, or current file's extension and mime.
- WP_Image_Editor_GD::_save()
Show all 50
- WP_Image_Editor_Imagick::_save()
- WP_Media_List_Table::column_title()Handles the title column output.
- WP_Query::get_posts()Retrieves an array of posts based on query variables.
- WP_Query::parse_tax_query()Parses various taxonomy related query vars.
- WP_REST_Attachments_Controller::edit_media_item()Applies edits to a media item and creates a new attachment record.
- WP_REST_Attachments_Controller::get_attachment_filename()Gets the attachment's original file name.
- WP_REST_Attachments_Controller::insert_attachment()Inserts the attachment post in the database. Does not update the attachment meta.
- WP_REST_Attachments_Controller::prepare_item_for_response()Prepares a single attachment output for response.
- WP_Site_Icon::create_attachment_object()Creates an attachment 'object'.
- _copy_image_file()Copies an existing image file.
- _wp_image_meta_replace_original()Updates the attached file and image meta data when the original image was edited.
- attachment_submitbox_metadata()Displays non-editable attachment metadata in the publish meta box.
- get_attachment_icon_src()Retrieve icon URL and Path.
- get_attachment_taxonomies()Retrieves taxonomies attached to given the attachment.
- get_media_item()Retrieves HTML form for modifying the image attachment.
- get_theme_data()Retrieve theme data from parsed theme file.
- image_downsize()Scales an image to fit a particular size (such as 'thumb' or 'medium').
- media_handle_sideload()Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
- media_handle_upload()Saves a file submitted from a POST request and create an attachment post for it.
- media_sideload_image()Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.
- verify_file_signature()Verifies the contents of a file against its ED25519 signature.
- wp_ajax_send_link_to_editor()Handles sending a link to the editor via AJAX.
- wp_calculate_image_srcset()A helper function to calculate the image sources to include in a 'srcset' attribute.
- wp_copy_parent_attachment_properties()Copy parent attachment properties to newly cropped image.
- wp_crop_image()Crops an image to a given size.
- wp_delete_attachment_files()Deletes all files that belong to the given attachment.
- wp_generate_attachment_metadata()Generates attachment meta data and create image sub-sizes for images.
- wp_get_attachment_image_src()Retrieves an image to represent an attachment.
- wp_get_attachment_thumb_file()Retrieves thumbnail for an attachment.
- wp_get_attachment_url()Retrieves the URL for an attachment.
- wp_image_add_srcset_and_sizes()Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
- wp_image_editor()Loads the WP image-editing interface.
- wp_image_src_get_dimensions()Determines an image's width and height dimensions based on the source file.
- wp_import_handle_upload()Handles importer uploading and adds attachment.
- wp_media_upload_handler()Handles the process of uploading media.
- wp_mime_type_icon()Retrieves the icon for a MIME type or attachment.
- wp_prepare_attachment_for_js()Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model.
- wp_print_theme_file_tree()Outputs the formatted file list for the theme file editor.
Source code
function wp_basename( $path, $suffix = '' ) { return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );}Changelog
Introduced in 3.1.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.0.4 tag, from
src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.