### Basic Theme Setup Function
Source: https://developer.wordpress.org/reference/hooks/after_setup_theme
This snippet provides a minimal example of a theme setup function that can be hooked into 'after_setup_theme'. It includes essential theme support features like title tags and post thumbnails.
```php
false,
'allowed' => null,
'blog_id' => 0,
);
$args = wp_parse_args( $args, $defaults );
$theme_directories = search_theme_directories();
if ( is_array( $wp_theme_directories ) && count( $wp_theme_directories ) > 1 ) {
/*
* Make sure the active theme wins out, in case search_theme_directories() picks the wrong
* one in the case of a conflict. (Normally, last registered theme root wins.)
*/
$current_theme = get_stylesheet();
if ( isset( $theme_directories[ $current_theme ] ) ) {
$root_of_current_theme = get_raw_theme_root( $current_theme );
if ( ! in_array( $root_of_current_theme, $wp_theme_directories, true ) ) {
$root_of_current_theme = WP_CONTENT_DIR . $root_of_current_theme;
}
$theme_directories[ $current_theme ]['theme_root'] = $root_of_current_theme;
}
}
if ( empty( $theme_directories ) ) {
return array();
}
if ( is_multisite() && null !== $args['allowed'] ) {
$allowed = $args['allowed'];
if ( 'network' === $allowed ) {
$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_network() );
} elseif ( 'site' === $allowed ) {
$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_site( $args['blog_id'] ) );
} elseif ( $allowed ) {
$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
} else {
$theme_directories = array_diff_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
}
}
$themes = array();
static $_themes = array();
foreach ( $theme_directories as $theme => $theme_root ) {
if ( isset( $_themes[ $theme_root['theme_root'] . '/' . $theme ] ) ) {
$themes[ $theme ] = $_themes[ $theme_root['theme_root'] . '/' . $theme ];
} else {
$themes[ $theme ] = new WP_Theme( $theme, $theme_root['theme_root'] );
$_themes[ $theme_root['theme_root'] . '/' . $theme ] = $themes[ $theme ];
}
}
if ( null !== $args['errors'] ) {
foreach ( $themes as $theme => $wp_theme ) {
if ( (bool) $wp_theme->errors() !== $args['errors'] ) {
unset( $themes[ $theme ] );
}
}
}
return $themes;
}
```
--------------------------------
### Example Usage of calendar_week_mod()
Source: https://developer.wordpress.org/reference/functions/calendar_week_mod
Demonstrates how to use the calendar_week_mod() function to get the number of days since the start of the week for day 10. The output is 3.
```php
echo calendar_week_mod( 10 );
```
--------------------------------
### Initialize Theme Customization and Preview
Source: https://developer.wordpress.org/reference/classes/wp_customize_manager/setup_theme
This method handles the initial setup for theme customization. It checks user capabilities, validates changeset data, and ensures the theme is ready for previewing. It also sets up actions for importing starter content and establishing the changeset.
```php
public function setup_theme() {
global $pagenow;
// Check permissions for customize.php access since this method is called before customize.php can run any code.
if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) {
if ( ! is_user_logged_in() ) {
auth_redirect();
} else {
wp_die(
'
' . __( 'You need a higher level of permission.' ) . '
' .
'' . __( 'Sorry, you are not allowed to customize this site.' ) . '
',
403
);
}
return;
}
// If a changeset was provided is invalid.
if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) {
$this->wp_die( -1, __( 'Invalid changeset UUID' ) );
}
/*
* Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer
* application will inject the customize_preview_nonce query parameter into all Ajax requests.
* For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out
* a user when a valid nonce isn't present.
*/
$has_post_data_nonce = (
check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false )
||
check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false )
||
check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false )
);
if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) {
unset( $_POST['customized'] );
unset( $_REQUEST['customized'] );
}
/*
* If unauthenticated then require a valid changeset UUID to load the preview.
* In this way, the UUID serves as a secret key. If the messenger channel is present,
* then send unauthenticated code to prompt re-auth.
*/
if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) {
$this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) );
}
if ( ! headers_sent() ) {
send_origin_headers();
}
// Hide the admin bar if we're embedded in the customizer iframe.
if ( $this->messenger_channel ) {
show_admin_bar( false );
}
if ( $this->is_theme_active() ) {
// Once the theme is loaded, we'll validate it.
add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) );
} else {
/*
* If the requested theme is not the active theme and the user doesn't have
* the switch_themes cap, bail.
*/
if ( ! current_user_can( 'switch_themes' ) ) {
$this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) );
}
// If the theme has errors while loading, bail.
if ( $this->theme()->errors() ) {
$this->wp_die( -1, $this->theme()->errors()->get_error_message() );
}
// If the theme isn't allowed per multisite settings, bail.
if ( ! $this->theme()->is_allowed() ) {
$this->wp_die( -1, __( 'The requested theme does not exist.' ) );
}
}
// Make sure changeset UUID is established immediately after the theme is loaded.
add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 );
/*
* Import theme starter content for fresh installations when landing in the customizer.
* Import starter content at after_setup_theme:100 so that any
* add_theme_support( 'starter-content' ) calls will have been made.
*/
if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) {
add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 );
}
$this->start_previewing_theme();
}
```
--------------------------------
### Working Best-Practice Minimal Example
Source: https://developer.wordpress.org/reference/functions/wp_schedule_event
A minimal, working example demonstrating scheduling a daily event using the 'init' hook and clearing it on deactivation. Includes a check to prevent rescheduling if an event is already scheduled.
```php
function svd_deactivate() {
wp_clear_scheduled_hook( 'svd_cron' );
}
add_action('init', function() {
add_action( 'svd_cron', 'svd_run_cron' );
register_deactivation_hook( __FILE__, 'svd_deactivate' );
if (! wp_next_scheduled ( 'svd_cron' )) {
wp_schedule_event( time(), 'daily', 'svd_cron' );
}
});
function svd_run_cron() {
// do your stuff.
}
```
--------------------------------
### Get Current URL with add_query_arg() in Subfolders
Source: https://developer.wordpress.org/reference/functions/add_query_arg
This example addresses an issue with add_query_arg() when WordPress is installed in a subfolder. It provides a corrected approach to avoid repeating subfolder paths in the URL.
```php
home_url( add_query_arg( null, null, null ));
```
--------------------------------
### Get Terms Filtered by First Letter
Source: https://developer.wordpress.org/reference/functions/get_terms
Fetches terms from a specific taxonomy where the term name starts with a given letter. This example includes a custom tax query modification for precise filtering.
```php
$authors = get_terms('book-authors', array('name__like' => $first_l));
function custom_tax_query( $pieces, $taxonomies, $args ) {
if ( 'book-authors' == $taxonomies[0] ) {
$pieces['where'] = str_replace("LIKE '%", "LIKE '", $pieces['where']);
}
return $pieces;
}
```
--------------------------------
### Twenty Fifteen Theme Setup Example
Source: https://developer.wordpress.org/reference/hooks/after_setup_theme
This example from the Twenty Fifteen theme shows how to register various theme features using the 'after_setup_theme' hook. It includes support for post thumbnails, title tags, custom backgrounds, and navigation menus.
```php
if ( ! function_exists( 'twentyfifteen_setup' ) ) :/** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which * runs before the init hook. The init hook is too late for some features, such * as indicating support for post thumbnails. * * @since Twenty Fifteen 1.0 */function twentyfifteen_setup() {/* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on twentyfifteen, use a find and replace * to change 'twentyfifteen' to the name of your theme in all the template files */load_theme_textdomain( 'twentyfifteen', get_template_directory() . '/languages' );// Add default posts and comments RSS feed links to head.add_theme_support( 'automatic-feed-links' );/* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded tag in the document head, and expect WordPress to * provide it for us. */add_theme_support( 'title-tag' );/* * Enable support for Post Thumbnails on posts and pages. * * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */add_theme_support( 'post-thumbnails' );set_post_thumbnail_size( 825, 510, true );// This theme uses wp_nav_menu() in two locations.register_nav_menus( array( 'primary' => __( 'Primary Menu', 'twentyfifteen' ), 'social' => __( 'Social Links Menu', 'twentyfifteen' ), ) );/* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );/* * Enable support for Post Formats. * * See: https://codex.wordpress.org/Post_Formats */add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat' ) );$color_scheme = twentyfifteen_get_color_scheme();$default_color = trim( $color_scheme[0], '#' );// Setup the WordPress core custom background feature.add_theme_support( 'custom-background', apply_filters( 'twentyfifteen_custom_background_args', array( 'default-color' => $default_color,'default-attachment' => 'fixed',) ) );/* * This theme styles the visual editor to resemble the theme style, * specifically font, colors, icons, and column width. */add_editor_style( array( 'css/editor-style.css', 'genericons/genericons.css', twentyfifteen_fonts_url() ) );}endif; // twentyfifteen_setupadd_action( 'after_setup_theme', 'twentyfifteen_setup' );
```
--------------------------------
### Filter: upgrader_pre_install
Source: https://developer.wordpress.org/reference/classes/wp_upgrader
Filters the installation response before the installation has started. Returning a WP_Error will short-circuit the installation.
```php
$res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
if ( is_wp_error( $res ) ) {
return $res;
}
```
--------------------------------
### Registering a navigation menu location (extended example)
Source: https://developer.wordpress.org/reference/functions/register_nav_menu
This is an extended example for registering a navigation menu. It also hooks into 'after_setup_theme' and registers a 'primary' menu, using a different text domain for translation.
```php
add_action( 'after_setup_theme', 'register_primary_menu' );
function register_primary_menu() {
register_nav_menu( 'primary', __( 'Primary Menu', 'theme-text-domain' ) );
}
```
--------------------------------
### Initialize WP_Filesystem and check writability
Source: https://developer.wordpress.org/reference/classes/wp_filesystem_direct/is_writable
This example shows how to initialize the WordPress filesystem and then use the is_writable() method. It includes error handling for filesystem initialization and demonstrates checking a file's writability.
```PHP
if (!\WP_Filesystem()) {
// failed to initialize file system.
return false;
}
global $wp_filesystem;
var_dump($wp_filesystem->is_writable('/path/to/file'));
```
--------------------------------
### Plugin Update and Install Notice Example
Source: https://developer.wordpress.org/reference/hooks/upgrader_process_complete
This comprehensive example shows how to use the 'upgrader_process_complete' hook to display custom notices to users after a plugin is updated or installed. It utilizes transients to manage the notice state.
```php
' . __( 'Thanks for updating', 'wp-upe' ) . '';
delete_transient( 'wp_upe_updated' );
}
}
add_action( 'admin_notices', 'wp_upe_display_update_notice' );
/**
* Show a notice to anyone who has just installed the plugin for the first time
* This notice shouldn't display to anyone who has just updated this plugin
*/
function wp_upe_display_install_notice() {
// Check the transient to see if we've just activated the plugin
if( get_transient( 'wp_upe_activated' ) ) {
echo '' . __( 'Thanks for installing', 'wp-upe' ) . '
';
// Delete the transient so we don't keep displaying the activation message
delete_transient( 'wp_upe_activated' );
}
}
add_action( 'admin_notices', 'wp_upe_display_install_notice' );
/**
* Run this on activation
* Set a transient so that we know we've just activated the plugin
*/
function wp_upe_activate() {
set_transient( 'wp_upe_activated', 1 );
}
register_activation_hook( __FILE__, 'wp_upe_activate' );
```
--------------------------------
### Get ID of a Blog by Name
Source: https://developer.wordpress.org/reference/functions/get_id_from_blogname
Example demonstrating how to get the ID of a specific blog using its slug.
```php
$slug = 'first-site';
$id = get_id_from_blogname( $slug );
```
--------------------------------
### Example WordPress Configuration Output
Source: https://developer.wordpress.org/reference/functions/bloginfo
This example shows a typical output of various blog information parameters, including URLs, names, and settings. Note that directory URLs are missing trailing slashes.
```text
admin_email = admin@example.com
atom_url = http://www.example.com/home/feed/atom
charset = UTF-8
comments_atom_url = http://www.example.com/home/comments/feed/atom
comments_rss2_url = http://www.example.com/home/comments/feed
description = Just another WordPress blog
home = http://www.example.com/home (DEPRECATED! use url option instead)
html_type = text/html
language = en-US
name = Testpilot
pingback_url = http://www.example.com/home/wp/xmlrpc.php
rdf_url = http://www.example.com/home/feed/rdf
rss2_url = http://www.example.com/home/feed
rss_url = http://www.example.com/home/feed/rss
siteurl = http://www.example.com/home (DEPRECATED! use url option instead)
stylesheet_directory = http://www.example.com/home/wp/wp-content/themes/largo
stylesheet_url = http://www.example.com/home/wp/wp-content/themes/largo/style.css
template_directory = http://www.example.com/home/wp/wp-content/themes/largo
template_url = http://www.example.com/home/wp/wp-content/themes/largo
text_direction = ltr
url = http://www.example.com/home
version = 3.5
wpurl = http://www.example.com/home/wp
```
--------------------------------
### Hook: upgrader_pre_install
Source: https://developer.wordpress.org/reference/classes/wp_upgrader/install_package
Filters the installation response before the installation has started. This hook is useful for pre-installation checks or modifications.
```php
apply_filters( 'upgrader_pre_install', bool|WP_Error $response, array $hook_extra )
```
--------------------------------
### Initialize WordPress Environment with WP::main()
Source: https://developer.wordpress.org/reference/classes/wp/main
This method sets up the WordPress environment by calling internal methods for request parsing, post querying, 404 handling, global registration, and header sending. It also triggers the 'wp' action hook.
```php
public function main( $query_args = '' ) {
$this->init();
$parsed = $this->parse_request( $query_args );
if ( $parsed ) {
$this->query_posts();
$this->handle_404();
$this->register_globals();
}
$this->send_headers();
/**
* Fires once the WordPress environment has been set up.
*
* @since 2.1.0
*
* @param WP $wp Current WordPress environment instance (passed by reference).
*/
do_action_ref_array( 'wp', array( &$this ) );
}
```
--------------------------------
### Import Theme Starter Content for Fresh Installs
Source: https://developer.wordpress.org/reference/classes/wp_customize_manager
Imports starter content for new WordPress installations when landing in the Customizer. This action is hooked to 'after_setup_theme' with a priority of 100 to ensure all theme support features are registered.
```php
if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) {
add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 );
}
```
--------------------------------
### Example: Get Category ID using get_category_by_slug()
Source: https://developer.wordpress.org/reference/functions/get_category_by_slug
This example demonstrates how to get a category object using its slug and then extract the category's term ID. It checks if the returned object is an instance of WP_Term before accessing its properties.
```php
$idObj = get_category_by_slug( 'category-slug' );
if ( $idObj instanceof WP_Term ) {
$id = $idObj->term_id;
}
```
--------------------------------
### Get Installed Plugins
Source: https://developer.wordpress.org/reference/classes/wp_plugin_dependencies
Retrieves a list of all installed plugins on the WordPress site. This function requires the 'plugin.php' file to be included.
```php
require_once ABSPATH . 'wp-admin/includes/plugin.php';
self::$plugins = get_plugins();
```
--------------------------------
### Example Usage of get_dirsize()
Source: https://developer.wordpress.org/reference/functions/get_dirsize
This example demonstrates how to use the get_dirsize() function to get the size of the WordPress directory and display it in MB.
```APIDOC
```php
```
```
--------------------------------
### Initialize Filesystem and Copy Directory
Source: https://developer.wordpress.org/reference/functions/copy_dir
This example demonstrates how to initialize the WordPress filesystem and then use copy_dir() to copy a directory. It includes checks for filesystem connection and ensures the target directory exists before copying.
```php
// Connecting to the filesystem.
if ( ! WP_Filesystem() ) {
// Unable to connect to the filesystem, FTP credentials may be required or something.
// You can request these with request_filesystem_credentials()
exit;
}
// Don't forget that the target directory needs to exist.
// If it doesn't already, you'll need to create it.
global $wp_filesystem;
$wp_filesystem->mkdir( $target_dir );
// Now copy all the files in the source directory to the target directory.
copy_dir( $src_dir, $target_dir );
```
--------------------------------
### Initialize Plugin Installation Strings
Source: https://developer.wordpress.org/reference/classes/plugin_upgrader/install_strings
Sets default strings for plugin installation stages. This method should be called before initiating a plugin installation.
```php
public function install_strings() {
$this->strings['no_package'] = __( 'Installation package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s…' ), '%s' );
$this->strings['unpack_package'] = __( 'Unpacking the package…' );
$this->strings['installing_package'] = __( 'Installing the plugin…' );
$this->strings['remove_old'] = __( 'Removing the current plugin…' );
$this->strings['remove_old_failed'] = __( 'Could not remove the current plugin.' );
$this->strings['no_files'] = __( 'The plugin contains no files.' );
$this->strings['process_failed'] = __( 'Plugin installation failed.' );
$this->strings['process_success'] = __( 'Plugin installed successfully.' );
/* translators: 1: Plugin name, 2: Plugin version. */
$this->strings['process_success_specific'] = __( 'Successfully installed the plugin %1$s %2$s.' );
if ( ! empty( $this->skin->overwrite ) ) {
if ( 'update-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Updating the plugin…' );
$this->strings['process_failed'] = __( 'Plugin update failed.' );
$this->strings['process_success'] = __( 'Plugin updated successfully.' );
}
if ( 'downgrade-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Downgrading the plugin…' );
$this->strings['process_failed'] = __( 'Plugin downgrade failed.' );
$this->strings['process_success'] = __( 'Plugin downgraded successfully.' );
}
}
}
```
--------------------------------
### Get Comment GUID
Source: https://developer.wordpress.org/reference/functions/get_comment_guid
Retrieves the feed GUID for a comment. Pass a comment ID or object; defaults to the global comment object. Returns the GUID string or false if the comment is not found.
```php
function get_comment_guid( $comment_id = null ) {
$comment = get_comment( $comment_id );
if ( ! is_object( $comment ) ) {
return false;
}
return get_the_guid( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID;
}
```
--------------------------------
### Prepare Plugin Install List Table Items
Source: https://developer.wordpress.org/reference/classes/wp_plugin_install_list_table/prepare_items
This is the main method for preparing the plugin installation list table. It includes necessary files, sets up global variables, determines the active tab, and prepares arguments for the plugin API query.
```php
public function prepare_items() {
require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
global $tabs, $tab, $paged, $type, $term;
$tab = ! empty( $_REQUEST['tab'] ) ? sanitize_text_field( $_REQUEST['tab'] ) : '';
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page.
$tabs = array();
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
if ( 'beta' === $tab || str_contains( get_bloginfo( 'version' ), '-' ) ) {
$tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' );
}
$tabs['featured'] = _x( 'Featured', 'Plugin Installer' );
$tabs['popular'] = _x( 'Popular', 'Plugin Installer' );
$tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' );
$tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' );
if ( current_user_can( 'upload_plugins' ) ) {
/*
* No longer a real tab. Here for filter compatibility.
* Gets skipped in get_views().
*/
$tabs['upload'] = __( 'Upload Plugin' );
}
$nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item.
/**
* Filters the tabs shown on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include
* 'featured', 'popular', 'recommended', 'favorites', and 'upload'.
*/
$tabs = apply_filters( 'install_plugins_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen.
*/
$nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs );
// If a non-valid menu tab has been selected, And it's not a non-menu action.
if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) {
$tab = key( $tabs );
}
$installed_plugins = $this->get_installed_plugins();
$args = array(
'page' => $paged,
'per_page' => $per_page,
// Send the locale to the API so it can provide context-sensitive results.
'locale' => get_user_locale(),
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
switch ( $type ) {
case 'tag':
$args['tag'] = sanitize_title_with_dashes( $term );
break;
case 'term':
$args['search'] = $term;
break;
case 'author':
$args['author'] = $term;
break;
}
break;
case 'featured':
case 'popular':
case 'new':
case 'beta':
$args['browse'] = $tab;
break;
case 'recommended':
$args['browse'] = $tab;
// Include the list of installed plugins so we can get relevant results.
$args['installed_plugins'] = array_keys( $installed_plugins );
break;
case 'favorites':
$action = 'save_wporg_username_' . get_current_user_id();
if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) {
$user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' );
// If the save url parameter is passed with a falsey value, don't save the favorite user.
if ( ! isset( $_GET['save'] ) || $_GET['save'] ) {
update_user_meta( get_current_user_id(), 'wporg_favorites', $user );
}
} else {
$user = get_user_option( 'wporg_favorites' );
}
if ( $user ) {
$args['user'] = $user;
} else {
$args = false;
}
add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 );
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Add Plugins screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs.
*
* Possible hook names include:
*
* - `install_plugins_table_api_args_favorites`
* - `install_plugins_table_api_args_featured`
* - `install_plugins_table_api_args_popular`
* - `install_plugins_table_api_args_recommended`
* - `install_plugins_table_api_args_upload`
* - `install_plugins_table_api_args_search`
* - `install_plugins_table_api_args_beta`
*
* @since 3.7.0
*
* @param array|false $args Plugin install API arguments.
*/
$args = apply_filters( "install_plugins_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = plugins_api( 'query_plugins', $args );
```
--------------------------------
### Get Last Modified Date from Response Header
Source: https://developer.wordpress.org/reference/functions/wp_remote_retrieve_header
Example of how to use wp_remote_retrieve_header() to fetch the 'last-modified' header from a remote GET request.
```php
$response = wp_remote_get( 'http://www.foo.com/file.txt' );
$last_modified = wp_remote_retrieve_header( $response, 'last-modified' );
```
--------------------------------
### Get Post ID from Attachment URL
Source: https://developer.wordpress.org/reference/functions/attachment_url_to_postid
Demonstrates how to get the post ID associated with an attachment URL. This is a basic usage example.
```php
echo attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
```
--------------------------------
### Example Usage of get_options()
Source: https://developer.wordpress.org/reference/functions/get_options
Demonstrates how to use the get_options() function to retrieve an array of common site options and then access individual options.
```php
$options = get_options( array(
'siteurl',
'blogname',
'blogdescription',
'posts_per_page',
'admin_email'
)
);
// print all options keys
print_r( $options );
// print single option key
echo esc_html( $options['admin_email'] );
```
--------------------------------
### WP_REST_Site_Health_Controller::get_directory_sizes
Source: https://developer.wordpress.org/reference/classes/wp_error/__construct
Gets the current directory sizes for this install.
```APIDOC
## GET /wp/v2/site-health/directory-sizes
### Description
Gets the current directory sizes for this install.
### Method
GET
### Endpoint
/wp/v2/site-health/directory-sizes
```
--------------------------------
### init()
Source: https://developer.wordpress.org/reference/classes/custom_background
Sets up the hooks for the Custom Background admin page, including adding the theme page and its associated actions.
```APIDOC
## init()
### Description
Sets up the hooks for the Custom Background admin page.
### Method
init
```
--------------------------------
### Plugin_Installer_Skin::__construct()
Source: https://developer.wordpress.org/reference/classes/plugin_installer_skin/__construct
Initializes the Plugin_Installer_Skin class, setting up the plugin installer interface with default or provided arguments.
```APIDOC
## Plugin_Installer_Skin::__construct( array $args = array() )
### Description
Sets up the plugin installer skin.
### Parameters
* **$args** (array) - Optional - Default: `array()` - An array of arguments to configure the skin. Expected keys include 'type', 'url', 'plugin', 'nonce', 'title', and 'overwrite'.
### Source
`wp-admin/includes/class-plugin-installer-skin.php`
```php
public function __construct( $args = array() ) {
$defaults = array(
'type' => 'web',
'url' => '',
'plugin' => '',
'nonce' => '',
'title' => '',
'overwrite' => '',
);
$args = wp_parse_args( $args, $defaults );
$this->type = $args['type'];
$this->url = $args['url'];
$this->api = $args['api'] ?? array();
$this->overwrite = $args['overwrite'];
parent::__construct( $args );
}
```
```
--------------------------------
### Example Usage of get_current_theme()
Source: https://developer.wordpress.org/reference/functions/get_current_theme
This example demonstrates how to use the deprecated get_current_theme() function to get the current theme's name and then display it safely.
```php
$theme_name = get_current_theme();
echo esc_html( $theme_name );
```
--------------------------------
### Get Installed Plugins Data
Source: https://developer.wordpress.org/reference/classes/wp_plugin_dependencies/get_plugins
Retrieves an array of data for all installed WordPress plugins. It caches the results internally to improve performance on subsequent calls.
```php
protected static function get_plugins() {
if ( is_array( self::$plugins ) ) {
return self::$plugins;
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
self::$plugins = get_plugins();
return self::$plugins;
}
```
--------------------------------
### WPDB Constructor Example
Source: https://developer.wordpress.org/reference/classes/wpdb
Initializes the WPDB class and establishes a database connection. It handles error display settings and configuration checks.
```php
public function __construct(
$dbuser,
#["SensitiveParameter"]
$dbpassword,
$dbname,
$dbhost
) {
if ( WP_DEBUG && WP_DEBUG_DISPLAY ) {
$this->show_errors();
}
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
// wp-config.php creation will manually connect when ready.
if ( defined( 'WP_SETUP_CONFIG' ) ) {
return;
}
$this->db_connect();
}
```
--------------------------------
### install_blog()
Source: https://developer.wordpress.org/reference/functions/install_blog
Installs an empty blog, creating the necessary database tables and options. Note: This function is deprecated as of WordPress 5.1.0. It is recommended to use switch_to_blog() before calling this function if invoking it directly.
```APIDOC
## install_blog( int $blog_id, string $blog_title = '' )
### Description
Creates the new blog tables and options. If calling this function directly, be sure to use switch_to_blog() first, so that $wpdb points to the new blog.
### Parameters
#### Path Parameters
- **blog_id** (int) - Required - The value returned by wp_insert_site().
- **blog_title** (string) - Optional - The title of the new site. Defaults to ''
### Source
`wp-includes/ms-deprecated.php`
```php
function install_blog( $blog_id, $blog_title = '' ) {
global $wpdb, $wp_roles;
_deprecated_function( __FUNCTION__, '5.1.0' );
// Cast for security.
$blog_id = (int) $blog_id;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$suppress = $wpdb->suppress_errors();
if ( $wpdb->get_results( "DESCRIBE {$wpdb->posts}" ) ) {
die( '' . __( 'Already Installed' ) . '
' . __( 'You appear to have already installed WordPress. To reinstall please clear your old database tables first.' ) . '