Note: The file descriptions on this page are for WordPress Version 2.x
Each file appearing in this list has been sorted into its directory of origin. A description of the purpose of the file and its possible dependencies appear after each.
Contents
- 1 WordPress Root
- 2 wp-admin
- 3 wp-admin/images
- 4 wp-admin/import
- 5 wp-content
- 6 wp-content/plugins
- 7 wp-content/themes
- 8 wp-content/themes/themedir
- 9 wp-content/themes/themedir/images
- 10 wp-includes
- 11 wp-includes/images
- 12 wp-includes/images/smilies
- 13 wp-includes/js
- 14 wp-includes/js/tinymce
- 15 wp-includes/languages
WordPress Root
- index.php
- Core WordPress index. This is the file that produces the blog output.
- license.txt
- The WordPress GPL license file.
- my-hacks.php
- Contains supplemental routines that are processed before output is produced. This is not included in the default install, but is referenced by the administration page if available.
- readme.html
- Pre-install information about WordPress.
- wp-atom.php
- Produces Atom syndication output.
- wp-blog-header.php
- Decides what to display based on the parameters that are passed to the blog. Included from any page that wants to display WordPress content.
- wp-cron.php
- wp-comments-post.php
- Receives posted comments and adds them to the database.
- wp-commentsrss2.php
- Produces RSS2 syndication output of post comments.
- wp-config-sample.php
- A sample configuration file for connecting WordPress to your MySQL database.
- wp-config.php
- The actual configuration file used to connect WordPress to your MySQL database. This is not included in the default install, but must exist for successful operation of WordPress. You may need to edit this file to modify certain configuration settings.
- wp-feed.php
- Decides the type of feed to produce based on a request and re-routes to the correct feed-producing file.
- wp-links-opml.php
- Produces OPML output of Links that were added to the blog via the WordPress admin menu.
- wp-login.php
- The WordPress login page for registered users.
- wp-mail.php
- Used for obtaining blog posts that were submitted via email. The URL of this file is usually added to a cron job so that it is regularly retrieved, so that new email posts are accepted.
- wp-pass.php
- Accepts the password needed to view password-protected posts, then redirects back to the protected post.
- wp-rdf.php
- Produces RDF syndication output.
- wp-register.php
- Allows new users to register usernames in WordPress via an online form.
- wp-rss.php
- Produces RSS syndication output.
- wp-rss2.php
- Produces RSS2 syndication output.
- wp-settings.php
- Performs various pre-execution routines, including checking for correct installation, including auxiliary functions, applying user plugins, initializing execution timers, etc.
- wp-trackback.php
- Handles incoming trackback requests.
- wp.php
- A very simple template for displaying blog posts. Does not include a lot of the fancy but fragile features of index.php.
- xmlrpc.php
- Handles incoming xmlrpc commands. Among other things, this allows posting without using the built-in web-based administrative interface.
wp-admin
- wp-admin/admin.php
- The core of the admin files. Connects to the database, integrates the dynamic menu data, displays non-core console (dashboard) pages, etc.
- wp-admin/admin-db.php
- wp-admin/admin-footer.php
- Contains the bottom of the admin console. Included from each of the console pages.
- wp-admin/admin-functions.php
- Contains various functions used by the admin console.
- wp-admin/admin-header.php
- Contains the top half of the admin console. Includes menu-header.php for menu logic.
- wp-admin/bookmarklet.php
- The pop-up page that is displayed when using the bookmarklet. Uses the default edit-form.php page for post input.
- wp-admin/categories.php
- Admin console page for category management. See: Manage — Categories
- wp-admin/cat-js.php
- wp-admin/edit.php
- Admin console for post management. See: Manage — Posts
- wp-admin/edit-comments.php
- Admin console page for comment management. See: Manage — Comments
- wp-admin/edit-form-advanced.php
- Admin console page for the advanced post editing form. Included from post.php. See: Write — Write Post — Advanced
- wp-admin/edit-form.php
- Admin console page for the simple post editing form. Included from post.php. See: Write — Write Post
- wp-admin/edit-form-comment.php
- Edits a specific post comment.
- wp-admin/edit-form-ajax-cat.php
- wp-admin/edit-link-form.php
- wp-admin/edit-page-form.php
- Admin console page for editing pages. Included from post.php and page-new.php. See: Write — Write Page
- wp-admin/edit-pages.php
- Admin console for page management. See: Manage — Pages
- wp-admin/execute-pings.php
- wp-admin/import.php
- wp-admin/index.php
- The administrative default page. Redirects to an appropriate page based on user access.
- wp-admin/inline-uploading.php
- wp-admin/install-helper.php
- A set of functions for database maintenance, including the popular-in-plugins maybe_create_table() and maybe_add_column().
- wp-admin/install.php
- Installs WordPress.
- wp-admin/link-add.php
- Admin console page to add links. See: Links — Add Link
- wp-admin/link-categories.php
- Admin console page for link category management. See: Links — Link Categories
- wp-admin/link-import.php
- Admin console page used to import links. See: Links — Import Links
- wp-admin/link-manager.php
- Admin console page for link management. See: Links — Manage Links
- wp-admin/link-parse-opml.php
- Contains functions used to parse an OPML file when importing links.
- wp-admin/list-manipulation.js
- wp-admin/list-manipulation.php
- wp-admin/menu-header.php
- The file used to display the menu in the admin interface.
- wp-admin/menu.php
- The default admin menu structure.
- wp-admin/moderation.php
- Contains functions related to comments moderation.
- wp-admin/options.php
- Admin console file that can be used to change every settings in one update.
- wp-admin/options-discussion.php
- Admin console page to manage options regarding comments and trackbacks. See: Options — Discussion
- wp-admin/options-general.php
- Admin console page to manage options regarding basic configuartion settings. See: Options — General
- wp-admin/options-head.php
- wp-admin/options-misc.php
- Admin console page to manage options regarding file uploads, link tracking and support for custom «hacks». See: Options — Miscellaneous
- wp-admin/options-permalink.php
- Admin console page to manage options regarding permalinks. See: Options — Permalinks
- wp-admin/options-reading.php
- Admin console page to manage options regarding how the information from your site is sent to a reader’s web browser or other application. See: Options — Reading
- wp-admin/options-writing.php
- Admin console page to manage options regarding the interface with which you write new posts. See: Options — Writing
- wp-admin/page-new.php
- Admin console page to create a new page.
- wp-admin/plugin-editor.php
- Admin console page to edit a plugin file.
- wp-admin/plugins.php
- Admin console page to manage plugins.
- wp-admin/post.php
- Admin console page to create a new post.
- wp-admin/profile-update.php
- wp-admin/profile.php
- Admin console page to manage your profile.
- wp-admin/setup-config.php
- Admin console page to create the wp-config.php file for the first time.
- wp-admin/sidebar.php
- wp-admin/templates.php
- Admin console page to edit any server-writeable file.
- wp-admin/theme-editor.php
- Admin console page to edit any file within a specific theme.
- wp-admin/themes.php
- Admin console page to manage themes.
- wp-admin/update-links.php
- wp-admin/upgrade-functions.php
- Contains functions related to version upgrading.
- wp-admin/upgrade-schema.php
- Contains default MySQL tables structure and default options, used when upgrading.
- wp-admin/upgrade.php
- Admin console page to upgrade froma lower version to a higher one.
- wp-admin/user-edit.php
- Admin console page to edit a user.
- wp-admin/users.php
- Admin console page to manage users.
- wp-admin/wp-admin.css
- The default stylesheet for the administrative console.
- wp-admin/xfn.js
wp-admin/images
This directory holds images associated and used by WordPress in the Administration Panels.
- wp-admin/images/box-bg.gif
- wp-admin/images/boxbg-left.gif
- wp-admin/images/boxbg-right.gif
- wp-admin/images/box-butt.gif
- wp-admin/images/box-butt-left.gif
- wp-admin/images/box-butt-right.gif
- wp-admin/images/box-head.gif
- wp-admin/images/box-head-left.gif
- wp-admin/images/browse-happy.gif
- wp-admin/images/fade-butt.png
- wp-admin/images/notice.gif
- wp-admin/images/toggle.gif
- wp-admin/images/wordpres-logo.png
wp-admin/import
- wp-admin/import/b2.php
- Used for importing posts from b2. See: Importing Content — b2
- wp-admin/import/blogger.php
- Used for importing posts from Blogger. See: Importing Content — Blogger
- wp-admin/import/dotclear.php
- wp-admin/import/greymatter.php
- Used for importing posts from Greymatter. See: Importing Content — Greymatter
- wp-admin/import/livejournal.php
- Used for importing posts from LiveJournal. See: Importing Content — LiveJournal
- wp-admin/import/mt.php
- Used for importing posts from Movable Type. See: Importing Content — Movable Type
- wp-admin/import/rss.php
- Used to import posts via RSS. See: Importing Content — RSS
- wp-admin/import/textpattern.php
- Used for importing posts from TextPattern. See: Importing Content — Textpattern
wp-content
This directory is typically not upgraded.
The /wp-content/ directory is for user-supplied content. WordPress upgrades are supposed to specifically avoid doing anything to any of the contents of this directory, unless the user wants the latest version of the default WordPress Themes.
WordPress Themes and WordPress Plugins are stored in this directory.
wp-content/plugins
All WordPress plugins are placed in this directory. The default plugin shipped with WordPress is an example plugin mostly for plugin developers, the Hello Dolly plugin, which displays random lines of the song «Hello Dolly.» Current versions also inlude the Akismet comment spam fighting WordPress Plugin as an option.
- wp-content/plugins/hello.php
- wp-content/plugins/akismet.php
wp-content/themes
All WordPress Theme data is placed within this directory in its own folder such as example.com/wp-content/themes/themedirectory/.
wp-content/themes/themedir
All files associated with a WordPress Theme are stored in their own directory under the wp-content/themes/themedir directory. As an example of the Theme files, the typical files included in the WordPress Default Theme under /wp-content/themes/default/ would be:
- wp-content/themes/themedir/comments.php
- Used to manage how the comments are displayed.
- wp-content/themes/themedir/footer.php
- Used to manage the footer of the pages.
- wp-content/themes/themedir/header.php
- Used to manage the header of every page.
- wp-content/themes/themedir/index.php
- Used to manage how the posts are displayed in your homepage.
- wp-content/themes/themedir/search.php
- Used to display a search form to search for entries.
- wp-content/themes/themedir/sidebar.php
- Used to manage the sidebar.
- wp-content/themes/themedir/style.css
- The main CSS file of WordPress.
wp-content/themes/themedir/images
Some WordPress Themes store images in a subdirectory under their Theme folder. For example, images used by the default theme are in wp-content/themes/default/images/.
wp-includes
- wp-includes/cache.php
- wp-includes/capabilities.php
- wp-includes/class-IXR.php
- The Incutio XML-RPC Library. Contains XML RPC support functions. Supplied by http://scripts.incutio.com/xmlrpc/
- wp-includes/classes.php
- Contains basic classes including the core post-fetching mechanism, WP_Query, and the rewrite manger, WP_Rewrite.
- wp-includes/class-pop3.php
- Contains a support class for accessing POP mailboxes. Used by wp-mail.php
- wp-includes/class-snoopy.php
- Snoopy is a PHP class that simulates a web browser. It automates the task of retrieving web page content and posting forms, for example.
- wp-includes/comment-functions.php
- wp-includes/default-filters.php
- wp-includes/feed-functions.php
- wp-includes/functions-compat.php
- Contains support functions that are present in newer PHP versions that are used only when running on older PHP versions.
- wp-includes/functions-formatting.php
- Contains support functions for cleaning XHTML and formatting text correctly in certain character sets.
- wp-includes/functions-post.php
- Contains support functions for managing posts in the database, querying user capabilities, fetching and writing comments, etc.
- wp-includes/functions.php
- Contains numerous vital support functions. Largest file in WordPress — almost double the next largest file.
- wp-includes/gettext.php
- Part of the PHP-gettext GPL translation library.
- wp-includes/kses.php
- Contains functions that are used to render and filter HTML in posts or comments.
- wp-includes/links.php
- Contains functions that are used to manage and use the Links feature of WordPress.
- wp-includes/locale.php
- Contains functions to replace default weekdays and months values.
- wp-includes/pluggable-functions.php
- wp-includes/registration-functions.php
- wp-includes/rss-functions.php
- wp-includes/streams.php
- Contains a class to wrap file streams, string streams.
- wp-includes/template-functions-author.php
- Contains theme functions related to the author of a post or a comment.
- wp-includes/template-functions-category.php
- Contains theme functions related to categories.
- wp-includes/template-functions-comment.php
- Contains theme functions related to comments.
- wp-includes/template-functions-general.php
- Contains general theme functions.
- wp-includes/template-functions-links.php
- Contains theme functions related to links
- wp-includes/template-functions-post.php
- Contains theme functions related to posts.
- wp-includes/template-functions.php
- Contains all the «template-» files above.
- wp-includes/template-loader.php
- wp-includes/vars.php
- Used to set miscellaneous variables.
- wp-includes/version.php
- Used to set the currently used WordPress version.
- wp-includes/wp-db.php
- Contains functions used to connect to the MySQL database.
- wp-includes/wp-l10n.php
- Contains functions used in multi-language support.
wp-includes/images
wp-includes/images/smilies
This is the directory that holds the smilies (emoticons) used in WordPress if the option is turned on. See Using Smilies for the full list.
wp-includes/js
- wp-includes/js/quicktags.js
- Javascript file that contains functions to manage the tags toolbox when editing posts or pages.
wp-includes/js/tinymce
This directory includes the files that run the Rich Text Editor in the Write Post panel.
wp-includes/languages
See: WordPress Localization
WordPress состоит из 3 папок wp-includes
, wp-admin
, wp-content
и из нескольких файлов рядом с этими папками.
Все файлы и папки, кроме wp-content
— это и есть WordPress, движок. Т.е. каталоги: wp-includes
и wp-admin
— это ядро WordPress, а wp-content
— это все остальное — все пользовательские данные…
В директории wp-content
хранятся практически все пользовательские файлы, кроме файла конфигурации wp-config.php (это неотъемлемая часть ядра). Здесь находятся плагины, темы, файлы плагинов, тем и содержимого сайта. Тут же принято хранить все файлы связанные с расширением возможностей WordPress.
Исходно в WordPress, wp-content
содержит один файл index.php и 3 папки: plugins, themes, languages.
Файл wp-content/index.php
Всегда должен существовать и должен иметь такое содержимое:
<?php // Silence is golden.
Этот файл запрещает видеть список файлов в папке. Если index.php не существует, а ваш веб-сервер позволяет смотреть файлы в директориях, то пройдя по ссылке http://example.com/wp-content
, можно увидеть все файлы и папки в этой директории. Это могут использовать хакеры, чтобы получить доступ к файлам ключей, что позволит взломать сайт. Например, если у вас установлен уязвимый плагин, то сайт можно будет легко проверить на наличие этого уязвимого плагина, а дальше атакующий без особого труда сможет сломать сайт.
При обновлении WordPress вручную, никогда не трогайте папку wp-content и ничего в ней. Она к обновлению WordPress никакого отношения не имеет.
Список того, что может находиться в каталоге wp-content:
/mu-plugins — обязательные плагины
В WordPress есть «Обязательные плагины», они находится в директории wp-content/mu-plugins
. О них я писал отдельно, обязательно ознакомьтесь!
Коротко об обязательных плагинах: Обязательные к использованию плагины (Must-use plugins), известные также под названием mu-plugins — это плагины, которые устанавливаются в специальную папку mu-plugins в каталоге контента wp-content и активируются автоматически (всегда активны) для сайта и сайтов сети. Эти плагины не видно среди обычных плагинов. В админ-панели они отображаются в верхней информационной строке и их невозможно отключить, кроме как удалить файл плагина из каталога wp-content/mu-plugins
.
/plugins — плагины
Плагины находятся в директории wp-content/plugins
. Плагин может представлять собой один файл или несколько файлов внутри папки. Любые файлы в директории /plugins
сканируются WordPress, чтобы определить, является ли файл файлом плагина. Если файл определяется как плагин, он появляется в админ-панели в разделе «Плагины» и готов к активации.
Для деактивации плагина можно удалить плагин из папки /plugins
. Также можно переименовать название папки, в этом случае, WordPress просто не сможет найти файл плагина и деактивирует при попытке подключения. Но имейте ввиду, что плагины лучше удалять из админ-панели, через кнопку Удалить, потому что при удалении срабатывают некоторые функции, которые подчищают данные плагина в базе данных или в файлах.
/themes — темы
Темы хранятся в директории wp-content/themes
. Каждая тема должна находиться в собственной папке и содержать правильно оформленный файл style.css, чтобы WordPress распознал ее как тему, пригодную для использования. В директории темы должны находиться как минимум 2 файла: index.php и style.css.
WordPress может хранить в этой директории сколько угодно тем. Вы можете легко посмотреть любую имеющуюся тему или активировать её во вкладке Внешний вид ► Темы
в админ-панели.
WordPress хранит загруженные файлы в папке wp-content/uploads
. Эта директория не существует в дистрибутиве WordPress по умолчанию. Она создается при первой загрузке файла в WordPress. Отдельное создание необходимо, потому что эта папка может быть перемещена в другое место (см. ниже)
По умолчанию WordPress хранит загрузки в папках по годам и месяцам:
/wp-content/uploads/2012/06/image.png
Перед тем как можно будет загружать какие-либо изображения или файлы в WordPress, на сервере необходимо разрешить создание папок в директории /wp-content
. При загрузке первого изображения WordPress автоматически создает директорию /uploads
и необходимые поддиректории в ней. После того как первый файл загружен, верните права для /wp-content обратно, обычно 755. Некоторые серверы сразу позволяют скрипту создавать папки и файлы.
Директория uploads должна иметь все права, чтобы в ней можно было свободно создавать и удалять файлы, обычно это права 777.
WordPress НЕ умеет распознавать и импортировать в админку изображения загруженные в uploads напрямую (не через админку). И в библиотеке файлов WordPress такие файлы не отображаются — WordPress о них ничего не знает.
uploads в Multisite
В Multisite установке для основного сайта фалы загружаются как обычно. А для всех дополнительных сайтов, создается папка /wp-content/uploads/sites/2
, где 2 — это ID сайта сети.
Так для каждого сайта создается папка с его ID в папке /wp-content/uploads/sites
. Далее файлы также располагаются в папках по году и месяцу.
Такой подход позволяет разделить загрузки для каждого сайта и упрощает их обслуживание.
До версии WP 3.5 файлы дополнительных сайтов располагались не в /wp-content/uploads/sites
, а в /wp-content/blogs.dir
.
Так например, директория для сайта с ID 3 выглядит так:
- WP 3.5 и выше:
/wp-content/uploads/sites/3
- WP 3.4 и ниже:
/wp-content/blogs.dir/3
Перемещение папки uploads
Чтобы переместить папку uploads
нужно определить константу UPLOADS в wp-config.php так:
define('UPLOADS', 'uploads'); // значит что папка uploads должна лежать в корне сайта
Или можно изменить опции: upload_path
и upload_url_path
в таблице опций (см. update_option()).
/upgrade — автообновления
Директория wp-content/upgrade
создается WordPress автоматически при обновлении WordPress. Эта папка используется для хранения новой версии WordPress, скачанной с WordPress.org. Перед обновлением, WordPress скачивает архив и извлекает его содержимое в эту папку. Чтобы процесс автоматического обновления протекал успешно, рекомендуется не трогать эту папку. Если данная директория удалена, WordPress создаст её при следующем обновлении.
/languages — переводы
Каталог wp-content/languages
присутствует только в том случае, если вы устанавливаете не английскую версию WordPress. В нем содержаться все файлы локализации (перевода) WordPress. Такие файлы имеют расширения:
.mo
— сжатая версия аналогичного .po файла, которая используется при переводе;.po
— исходный файл перевода. Этот файл можно использовать для редактирования перевода. После редактирования его нужно скомпилировать в сжатую версию с расширением.mo
.
Также в languages
могут находиться специальные поддиректории:
-
/pliugns
— содержит переводы плагинов. Файл перевода должен иметь формат:название плагина-локаль.mo
, например:akismet-ru_RU.mo
. Перед загрузкой своего файла перевода, плагин проверяет наличие файла перевода в этой папке и если он там есть, то используется этот файл перевода, а не родной перевод плагина. /themes
— содержит переводы тем. Файл перевода должен иметь формат:название темы-локаль.mo
, например:twentyfifteen-ru_RU.mo
. Также как и с плагинами — эти файлы имеют больший приоритет перед родными файлами перевода темы.
Произвольные директории
В /wp-content
можно создавать любые директории. Некоторые плагины, создают такие папки для хранения файлов. Обычно отдельная папка создается, когда нужно хранить много файлов или когда хранимые файлы как-то отличаются от остальных.
Например плагин WP Super Cache создает директорию /wp-content/cache
для хранения кэшированных страниц сайта. Кэшированная страница — это сгенерированная страница сайта, сохраненная как статический файл HTML. При обращении к такой странице она не генерируется повторно, а отдается статический файл. Это и есть страничный кэш, который уменьшает нагрузку сервера в десятки раз, поскольку страницы не генерируются при каждом просмотре, а создаются только когда кэш перезаписывается.
Плагин WP Super Cache также добавляет два файла в директорию wp-content: advanced-cache.php (специальный) и wp-cache-config.php. Они нужны для работы WP Super Cache.
Другой пример, популярный плагин для галерей — NextGen Gallery — создает директорию /wp-content/gallery
для хранения изображений, загруженных в галереи. Каждая созданная галерея представляет собой поддиректорию /gallery
.
Еще пример, мой плагин Kama Thumbnail, который также создает папку /wp-content/cache/thumb
и записывает в нее созданные файлы миниатюр.
Специальные файлы
advanced-cache.php
Вызывается на самом раннем этапе загрузки WordPress, в файле wp-settings.php, если константа WP_CACHE включена. Вот так выглядит вызов:
if ( WP_CACHE && apply_filters( 'enable_loading_advanced_cache_dropin', true ) && file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ) ) { // Для использования плагинами кэширования. Использует статический файл для обрыва работы скрипта. include WP_CONTENT_DIR . '/advanced-cache.php'; // Re-initialize any hooks added manually by advanced-cache.php. if ( $wp_filter ) { $wp_filter = WP_Hook::build_preinitialized_hooks( $wp_filter ); } }
Этот файл используется плагинами страничного кэширования. В нем обычно проверяется наличие подходящего файла кэша и если он есть, то он выводиться на экран и работа скрипта обрывается. Это позволяет не загружать 90% файлов WordPress и отдавать статические HTML файлы.
object-cache.php
В отличии от advanced-cache.php
, object-cache.php
срабатывает всегда, если он существует. Он нужен, чтобы переопределить работу базового кэширования объектов WordPress.
Вызывается из функции wp_start_object_cache(), которая в свою очередь вызывается из файла wp-settings.php чуть позднее advanced-cache.php
.
На основе этого файла работают такие кэши объектов как: Memcache, Memcached, APC, XCache.
Вызов выглядит так:
// Запускает объектное кэширование WordPress или // внешнее объектное кэширование, если существует специальный файл. wp_start_object_cache();
С версии WP 5.8 появился хук enable_loading_object_cache_dropin, который позволяет отключить плагин объектного кэширования. Хук вызывается раньше чем загружаются плагины и нужен когда код запускается не с веба, например при тестах.
maintenance.php
wp-content/maintenance.php
отвечает за вывод страницы-заглушки, которая показывается в момент автообновления WoordPress. Такая страница определена по умолчанию и за её вывод отвечает функция wp_maintenance(). Но если создать файл maintenance.php в wp-content, то за вывод страницы-заглушки будет отвечать содержимое этого файла.
В maintenance.php нужно описать страницу-заглушку по всем правилам HTML.
Подробнее читайте в описании функции wp_maintenance()
db-error.php
Позволяет показать произвольный шаблон страницы ошибки соединения с базой данных.
Если файл wp-content/db-error.php
существует в папке wp-content
, тогда вместо дефолтного сообщения WordPress об ошибки соединения с базой данных будет загружен этот файл. В файле нужно создать HTML код страницы об ошибке!
Страница об ошибке подключения должна устанавливать статус ответа 500, чтобы поисковики не обрабатывали контент.
Файл db-error.php вызывается функцией dead_db(), а функция в свою очередь вызывается при ошибке подключения к БД.
Пример такой страницы смотрите здесь.
sunrise.php
Загружается только для мультисайтовой сборки, т.е. когда срабатывает условие is_multisite() и при этом определена константа ‘SUNRISE’ (её нужно определить в файле wp-config.php).
Файл wp-content/sunrise.php
позволяет на раннем этапе изменить логику работы сайта в сети мультисайт. Например, тут можно установить глобальные переменные $current_site,
$current_blog определяющие текущий сайт сети. Или можно изменить префикс таблиц БД — переменная $table_prefix.
Также в файле sunrise.php можно изменить константы отвечающие за то, где находится каталоги MU плагинов или обычных плагинов. см. wp_plugin_directory_constants()
.
db.php
Позволяет переписать движок работы с БД. Если файл существует в папке wp-content
, то он будет вызван до создания подключения к БД. Далее, если в этом файле определить переменную $wpdb, то именно она будет использоваться, как глобальная переменная для работы с БД.
Благодаря такой логике, можно, например, расширить базовый класс wpdb{} или полностью его заменить.
Пример расширения базового класса wpdb{}:
<?php // это код для файла db.php, который лежит в папке wp-content defined( 'ABSPATH' ) || die(); if ( defined( 'DOING_CRON' ) && DOING_CRON ) return; class MY_DB extends wpdb { public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) { // дополнительный код... parent::__construct( $dbuser, $dbpassword, $dbname, $dbhost ); } // переопределяем метод wpdb::query() public function query( $query ) { // наш измененный код } } $wpdb = new QM_DB( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
Переименование или перемещение папки wp-content
В некоторых случаях, например, для уникализации многих URL на всем сайте или для объединения структуры сайта с другим скриптом, или по каким-то еще причинам, нужно чтобы каталог wp-content назвался по-другому или чтобы он находился в другой директории.
Переместить или переименовать wp-content очень просто. Для этого нужно открыть конфигурационный файл wp-config.php, который лежит в корне вашего сайта и определить в нем две константы:
WP_CONTENT_DIR
— путь до каталога контента;WP_CONTENT_URL
— URL на каталог контента.
define( 'WP_CONTENT_DIR', __DIR__ .'/data' ); define( 'WP_CONTENT_URL', 'http://'. $_SERVER['HTTP_HOST'] .'/data' );
Данный код переименовывает wp-content в data.
Папка wp-content — руководство для начинающих по наиболее важному каталогу WordPress
Доброго времени суток!
Сегодня я бы хотел рассказать вам о самом главном каталоге в установке WordPress — wp-content.
Что такое wp-content? Это может быть ваша первая реакция в качестве новичка WordPress или если вы в основном работаете с WordPress через бэкэнд. Ведь среднестатистический владелец сайта большую часть времени проводит в личном кабинете.
Это имеет смысл. В конце концов, вы можете выполнять все важные задачи здесь и иметь возможность позаботиться обо всем сайте без необходимости редактировать файлы, перемещать данные или выполнять другие утомительные задачи.
Ко мне часто поступают вопросы про хостинг, которым я пользуюсь и поэтому решил указать хостинг в статье https://sprinthost.ru. Вы можете попробовать попользоваться хостингом 30 дней бесплатно. Чтобы понять, как будет работать Ваш сайт на этом хостинге просто перенести свой сайт (в этом поможет поддержка хостинга бесплатно) и и таким образом сможете понять подходит хостинг Вам или нет. На этом хостинге находятся сайты с 20 000 тысяч посещаемость и сайты чувствуют себя отлично. Рекомендую! Да, если делать оплату на 1 год то получаете скидку 25%. И что мне нравится — тех. поддержка всегда помогает в технических вопросах, за что им спасибо. Как Вы понимаете не всегда проходит всё гладко и нет желания, чтобы сайт не был доступен тем самым страдал трафик и доход.
Если вы пошли на один шаг дальше и установили WordPress самостоятельно, вы даже можете быть в курсе его отдельных частей: установке базы данных и самого WordPress.
Однако, если вы не являетесь разработчиком или кем-то, кто любит контролировать все аспекты вашего сайта, вы, вероятно, не очень хорошо знакомы с файловой структурой WordPress и каждым из ее файлов и папок.
Одна из самых центральных его частей — папка wp-content. По этой причине, в этой статье я хочу подробно рассмотреть именно это. Мы поговорим о том, где находится wp-content, его назначение, что в нем содержится и что она позволяет делать.
Готовы окунуться в эту часть WordPress? Тогда поехали.
Если вы не внесли существенных изменений в свою файловую структуру или не переименовали wp-content во что-то еще (подробнее об этом ниже), вы должны найти его в середине вашей установки WordPress.
Как и wp-admin и wp-includes, wp-content является частью каждой стандартной установки WordPress и будет создаваться автоматически при каждой установке CMS на сервер.
Таким образом, чтобы получить к нему доступ, все, что вам нужно сделать, это войти на свой FTP-сервер (например, через FileZilla). В зависимости от настроек вашего хоста, вам может потребоваться перейти в другую папку, например public_html, чтобы попасть на ваш сайт, однако, как только вы там окажетесь, именно там вы найдете каталог wp-content.
Какова цель wp-content?
В более широком смысле, wp-content содержит весь предоставленный пользователем контент. В основном все, что вы можете загрузить на свой сайт, находится здесь. Заметьте, это не относится к тому, что вы пишете. Эти вещи хранятся в базе данных WordPress.
Однако, если у вас есть база данных и папка wp-content, вы всегда сможете вернуть свой сайт обратно, даже если все остальное было потеряно.
На самом деле, если у вас есть тестовый веб-сайт (ничего важного, например, сайт местной разработки ), вы можете попробовать небольшой эксперимент.
Сначала загрузите последнюю версию WordPress. Затем зайдите в главный каталог вашего тестового сайта. Здесь отметьте каждый файл и каталог, за исключением wp-content и wp-config.php (если он виден, вы также можете захотеть оставить файл .htaccess).
Затем удалите их. Вы меня правильно поняли, избавься от всей этой кучи. После того как вы это сделаете, при попытке загрузить свой сайт в браузер, он будет выглядеть примерно так:
Чтобы исправить ситуацию, перейдите на свежую версию WordPress, которую вы только что загрузили. Распакуйте архив и получите доступ к каталогу.
Здесь, опять же, отметьте все файлы и папки, за исключением тех, которые остались в вашей тестовой установке WordPress. Затем перепишите их.
После завершения, если вы сделали все правильно, теперь вы должны перезагрузить свой сайт без проблем и увидеть его именно таким, как он был раньше.
Благодаря папке wp-content и базе данных WordPress ничего особенного для вашего сайта не было потеряно. Аккуратно, правда?
Итак, что же тогда находится внутри wp-content?
Почему вышеуказанный эксперимент работает? Поскольку, как уже упоминалось, wp-content содержит все пользовательские данные, которые не хранятся в базе данных. Это становится еще более очевидным, когда вы открываете каталог.
Стандартные каталоги в папке wp-content
Как правило, wp-content будет содержать как минимум три каталога: плагины (plugins), темы (themes) и загрузки (uploads). Вот для чего они используются:
- Плагины. Как видно из названия, именно здесь WordPress хранит плагины. При установке плагина через меню в панели инструментов, он будет в конечном итоге здесь. И наоборот, можно также установить плагины вручную, извлекая и копируя их в этот каталог. Это сделает их доступными для активации в панели управления WordPress.
- Темы — аналогично папке плагинов, но для тем. Установите тему из бэкэнда и потом вы найдете ее в этом каталоге. Или скопируйте темы в эту папку, чтобы сделать их доступными в бэкэнде. Это также папка, в которой вы будете тратить много времени на создание или изменение собственной темы или дочерней темы.
- Загрузка — здесь WordPress хранит все ваши медиафайлы, такие как изображения, видео или другие файлы, которые вы загружаете на свой сайт. По умолчанию медиафайлы упорядочены в подпапках, обозначая год и месяц их добавления на сайт. Однако также возможно отключить эту опцию, и все файлы окажутся в одном каталоге.
Итак, это стандартная настройка WordPress. Однако, особенно на более авторитетных сайтах, вы часто найдете дополнительные папки внутри каталога wp-content.
Другие общие папки
В зависимости от плагинов, тем и других вещей, присутствующих на вашем сайте, вы также можете найти это внутри wp-content:
- Mu-plugins — это сокращение от обязательных плагинов. Плагины для обязательного использования поставляются с некоторыми темами и имеют решающее значение для работы вашей темы и сайта. Если они существуют, вы найдете их в этой папке.
- Languages (языки) — если ваш сайт не использует английский, но является одним из многих других языков, на которых доступна CMS, WordPress сохранит языковые файлы в этом каталоге.
- Upgrade (обновление) — это временная папка, созданная WordPress при обновлении сайта до новой версии.
Помимо этого, другие плагины могут иногда создавать свои собственные каталоги внутри wp-content. Например, W3 Total Cache и WP Super Cache могут хранить здесь некоторые файлы.
Как упоминалось ранее, это имеет смысл, поскольку этот каталог не перезаписывается при обновлении WordPress. По этой причине любые данные, которые необходимо сохранить, лучше всего сохранить здесь.
Тем не менее, конечно, это также означает, что wp-content имеет жизненно важное значение для любого сайта WordPress и всегда должен быть включен в резервную копию.
Когда использовать wp-content
Во время работы сайта WordPress, есть несколько случаев, в которых вам, возможно, придется иметь дело с этой директории. Помимо работы с темами, ниже приведены некоторые другие примеры, когда вам может потребоваться доступ к wp-content.
Исправление важных ошибок
Содержание wp-content иногда может быть причиной распространенных ошибок WordPress. В частности, те, которые вызваны плагинами и темами.
Когда это произойдет, и ваш сайт станет недоступным, вам, возможно, придется получить доступ к папке плагинов, чтобы деактивировать некоторые из них вручную и вернуться в WordPress бэкэнд.
Переименовать wp-content
Несмотря на свою жизненно важную функцию, название wp-content не высечено на камне. Вполне возможно изменить его на что-то другое (как, кстати, с папками внутри wp-content).
Зачем вам это может понадобиться? Короче говоря, безопасность.
Поскольку WordPress является открытым исходным кодом, любой желающий может выяснить основную структуру любого сайта. Стандартная настройка WordPress общеизвестна, что облегчает начало атаки.
По этой причине переименование wp-content является одним из шагов на пути к более безопасному сайту. Используйте эту статью, чтобы выяснить, как это реализовать. Для получения дополнительных советов о том, как сделать WordPress безопаснее, не пропустите мою статью на эту тему.
О wp-content в двух словах
Папка wp-content является неотъемлемой частью любой установки WordPress, поэтому вы найдете ее в главном каталоге любого сайта, построенного на платформе WordPress.
В нем размещается любой контент, предоставленный пользователями, который не сохраняется в базе данных. Это включает в себя плагины, темы и загруженные медиа. По этой причине, кроме базы данных, wp-content всегда должен быть частью резервной копии вашего сайта.
В этом кратком руководстве вы узнали, как получить доступ к wp-content и что вы можете найти в нем. Обладая этими знаниями, вы теперь немного знакомы с тем, как WordPress работает за кулисами.
Это, в свою очередь, дает вам больше контроля над вашим сайтом, и это никогда не может быть плохо.
У вас есть еще вопросы по wp-content? Если это так, пожалуйста, сообщите мне об этом в комментариях ниже.
До скорых встреч!
Юрич:
Занимаюсь созданием сайтов на WordPress более 6 лет. Ранее работал в нескольких веб-студиях и решил делиться своим опытом на данном сайте. Пишите комментарии, буду рад общению.
Are you curious about where the content of your website is stored? Or have you heard of wp-content on your WordPress site and want to learn more about it?
A WordPress website is made up of many files and folders. wp-content is one of the key folders as it contains your website’s content, and the themes and plugins installed on your site. If this folder is accidentally deleted, your website will crash.
At MalCare, we’ve seen many cases where WordPress websites crashed because a hacker has meddled with the wp-content. Since many website owners never visit the backend of WordPress and check the wp-content, it makes it an ideal spot for hackers to inject malware. They also hide backdoors that give them a secret entry point into your site.
Learning about what hackers can do the wp-content repository can be alarming. But don’t worry!
In this guide, we’ve simplified everything you need to know about the wp-content. You’ll find out what the folder does and how to use it. Next, you’ll learn how to hide it or prevent it from being accessed by unauthorized users.
TL;DR: The wp-content is an integral part of your WordPress site. To ensure it is protected, we recommend installing a WordPress Security Plugin (MalCare). The plugin will scan and protect your WordPress files and folders from hackers. It will also automatically take backups of your site regularly and store them safely.
What Is The WP-content Folder?
As we mentioned in the introduction, a WordPress website is made of many files and directories. It is created by default at the time of building your website and is one of the most crucial folders of your website.
Every image that you upload, every theme and plugin that you install on your website is stored in this folder (more details in the next section). In other words, any files that don’t get stored in the database are stored here. If the folder gets deleted, your website will crash and you will need to rebuild it from scratch.
Generally, website owners don’t use this folder. But certain occasions may arise when you need to access it.
For instance, we have installed a plugin on our WordPress website. But the plugin caused the site to malfunction as it was not compatible with the version of WordPress we were running. We couldn’t disable it on the WordPress dashboard. So we had to go to the wp-content folder to delete the plugin in order to access our site.
Recommend read: Beginner’s Guide to Understanding WordPress File Structure & Database
How To Access The WP-Content Folder
To access the wp-content folder, you need to access the WordPress root directory. Here’s what to do:
1. Log into your web hosting account (e.g. WP Engine).
2. Access cPanel and open File Manager.
3. Here, you will see a folder named ‘public_html’. This folder resides on your web server and is made up of WordPress files and sub-folders that all contribute to the functioning and appearance of your website.
4. Inside the public_html folder, you will find three main sub-folders:
- wp-admin – Contains administrative files related to who can access your WordPress panel and what permissions they are granted.
- wp-includes – Contains files related to rules, hierarchies, and settings of your WordPress site.
- wp-content – Contains your website’s themes and plugins files and media uploads (in wp content / uploads).
Today we will focus on the wp-content folder and learn more about its role on your website. The wp-content folder has many more sub-folders and files which we’ll discuss in the next section.
What Does The Wp-content Contain?
The wp-content folder on a standard WordPress site has three more subfolders – plugins, themes, and uploads.
However, as WordPress sites expand and add more plugins and themes, more folders may be created. To simplify this, we’ve broken down the directory structure of this section into four parts:
- Plugins Folder
- Themes Folder
- Uploads Folder
- Other Common Folders In Wp-content
- mu-plugins
- Languages
- Upgrade
- Specific Plugins
1. Plugins Folder
On your WordPress website, you have the ability to install plugins. All the plugins you install on your WordPress site (both active and inactive) are stored in this folder. If you open any of the folders, you’d find rules and configuration files of the plugins installed. Tampering with this folder could cause the plugins to misbehave.
Knowing how to access this folder can come in handy if you are unable to install a plugin on your dashboard (admin panel). You can copy the plugin’s zip file and paste it into this folder. Next, you have to extract the zip file to activate the plugin on your site.
Similarly, you can use the folder to delete or disable a plugin. Sometimes, a plugin might be causing a compatibility issue which causes the website to malfunction. If you are unable to disable the plugin from the dashboard, you can access this folder and disable it manually.
We do not recommend using this manual method as making changes directly to this WordPress folder is very risky. A slight misstep can render your site broken. Use this method only when you have no other choice.
2. Themes Folder
Similar to the plugins folder, this one houses all the themes on your site. You can use it the same way you would use the plugins folder.
When you install a theme on your WordPress dashboard, it would appear in this folder.
For instance, we installed the Astra theme on our site:
Next, we checked the themes folder and a sub-folder named ‘astra’ was automatically created:
You can also copy themes into this folder to make it available on your dashboard. In the same way, you can also delete themes here.
3. Uploads Folder
As the name suggests, everything that is uploaded to your site is stored in this folder. This includes images, videos, and any other files such as PDF documents, MS Word docs, and GIFs.
By default, these media files are stored in subfolders according to the year and month they were added to the site. You can think of it as a media library.
This is the default setup of a wp-content folder of a WordPress site. However, as WordPress sites expand and develop, you can often find additional folders here. We have briefly entailed them below:
4. Other Common Folders Inside Wp-content
There are four additional folders that are often created in the wp-content folder.
a) mu-plugins
mu-plugins are must-use plugins. These plugins are critical to the functioning of your WordPress site and are deemed as must use. For example, a plugin may come bundled with a theme. If you disable the plugin, it could break the theme and therefore, break your website. So developers tag them as mu-plugins so that you don’t disable them unintentionally. If such plugins exist on your site, they are stored in this folder.
b) Languages
WordPress can be used to create websites in many different languages. If you choose to use any language other than English or multiple languages, WordPress will save the language files in this folder.
c) Upgrade
This is a temporary folder created by WordPress when you update your site to a new version.
d) Specific Plugins
Sometimes plugins create their own directories on your website. This means they create their own folders within the wp-content folder. For example, the WP Super Cache plugin creates its own folder called ‘cache.’
You can see that the wp-content repository contains vital data on your website. Therefore, it should always be protected.
In the next section, we discuss the measures you can take to safeguard this folder from being tampered with or deleted by anyone.
How To Protect WP-content Or The Uploads Folder?
There are three measures you need to take to protect your wp-content and uploads folder:
- Take a backup of these folders
- Change the name of your wp-content folder
- Block the folder from showing on your website’s index
1. Backup Your WP-Content Repository
A backup is a copy of your website that can be used to restore your site to normal if anything were to go wrong with it like if you accidentally delete any file or hackers tamper with the folder.
You can take a backup using the BlogVault backup plugin. It’s easy to install and it will automatically take a complete backup of your WordPress site in under a few minutes. We recommend BlogVault because it’s guaranteed to work when you restore it.
You can also use the plugin to selectively restore your wp-content.
2. Change The Name Of Your Wp-content
As we know, by default, the folder that stores your content, themes, and plugins are named wp-content. This name is common across all WordPress sites which makes it easy for anyone to identify and locate the folder. This means if hackers find a way to break into your site they will be able to find this folder easily because they know it is named ‘wp-content’. You can protect this folder by changing its name.
There are two ways to do this – using a plugin or manually.
A. Using a Plugin (Safe)
We recommend doing this by using a plugin called WP Hide & Security Enhancer. It provides you with a simple way of hiding not just your wp-content, but other important WordPress files as well.
This plugin is great because it explains the process every step of the way. It’s easy for both beginners and pros to use. In addition to wp-content, you can also implement other protective measures on your site such as protecting your comments, authors, uploads, and more!
B. Manually (Not Recommended)
To rename your wp-content file manually, you need to access the folder on your web server and make changes to it. We strongly do not recommend using this method as the slightest mistake could break your site.
Step 1: Access your web hosting account. Go to cPanel, and access your website’s File Manager.
Step 2: Navigate to the wp-content folder, right-click on it, and select ‘Rename’.
Step 3: Rename the folder to any other name. Ensure it is unique and not a name that is already in use on your site.
3. Hide The WP-Contents Folder
There are times hackers request for your wp-content repository using malicious code with a URL in it. This folder’s URL path is usually yourdomain.com/wp-content or yourdomain.com/public_html/wp-content.
This URL path isn’t used in the address bar of your browser. Rather, it is used in the coding of your site. Hackers write malicious code to fetch the data of this folder or to inject their own malicious code.
You can block outsiders from accessing this URL path. Only users who are logged into your common WordPress dashboard will have access to it. To do this, you can use the same plugin we mentioned above or you can do it manually.
A. Using a Plugin (Safe)
Using WP Hide & Security Enhancer, you can block the wp-content URL path with two clicks.
Simply navigate to the option ‘Block wp-content URL’ and select yes. Once you save changes, the plugin will block your wp-content URL path.
B. Manually (Not Recommended)
This method requires adding code into a file called the .htaccess file. Modifying your WordPress files manually is very risky. A small error can cause your site to malfunction or even crash. That said if you still want to go ahead and give it a try, here are the steps:
Step 1: Access your web hosting account. Go to cPanel, and access your website’s File Manager.
Step 2: Navigate to the wp-content folder and create a new file and name it .htacess file.
Step 3: Right-click this file and choose ‘Edit’. Paste the following code and save changes.
Order Allow, Deny
Deny from all
Allow from all
In case you cannot see your .htaccess file after creating it, go to Settings and select ‘Show Hidden Files’.
Step 4: Your wp-contents folder will be hidden. If you try to access your file using https://www.yourdomain.com/wp-contents, you should see an error message:
With that, we come to an end on discussing the wp-content and uploads folder on your WordPress site. We are confident that you will now be fully aware of what this folder does, where to find it, and how to protect it now.
[ss_click_to_tweet tweet=”The wp-contents folder of your WordPress site is more than just a place that stores your content. Learn all about it in this guide.” content=”” style=”default”]
Final Thoughts
The wp-content folder is an integral part of your WordPress site. This makes it so important to take WordPress security measures to ensure it is protected and backed up.
Apart from the wp-content, there are other integral files and folders that need to be safeguarded. We recommend protecting not just one or two elements on your site, but your entire site.
To do this, we recommend installing the MalCare Security Plugin. It will scan your site regularly for malware and alert you if there’s anything suspicious on your site. You can also take a complete backup of your site regularly and store it in a safe offsite location.
Protect Your WordPress Site With MalCare!
if my main.php file is located inside /wp-content/plugins/myplugin/folder/folder/folder/
why including urls.php , located inside /wp-content/uploads/folder/
doesn’t work with this path:
include_once("../../../../../uploads/folder/urls.php");
it works only if placed inside same folder as main.php with path ('urls.php');
asked Oct 12, 2019 at 14:44
Nathan BernardNathan Bernard
3912 gold badges5 silver badges19 bronze badges
you can use content_url()
it’s located with http://www.example.com/wp-content
wp-content folder.
Or for path
you can use WP_CONTENT_DIR
it’ll located to wp-content
folder.
require_once(WP_CONTENT_DIR. 'uploads/folder/urls.php');
Check more info Documentation
answered Oct 12, 2019 at 14:59
Dilip HiraparaDilip Hirapara
14.6k3 gold badges26 silver badges49 bronze badges
4
It seems strange. Do you have any error message when you run your main.php?
Try to check again, maybe a typo somewhere. Do you take help of Text editor auto-completion when calling urls.php?
answered Oct 13, 2019 at 7:26