WordPress свой php скрипт

Исполняемый php код в записях WordPress

Бывают ситуации, когда очень удобно использовать весь потенциал языка программирования PHP в тексте при написании статей. Речь идет о статьях для WordPress.

Все кто пробовал написать какой либо php код в посте, в надежде что он сработает, знают, что WordPress воспринимает такой код как простой текст. Однако иногда бывает удобно запустить, например, какой-нибудь цикл вывода прямо в тексте при написании статьи, ведь контент такой статьи будет обновляться динамически. Другим примером может служить возможность вызывать готовые функции в посте, в случае необходимости или, например, вставить какой-нибудь php файл в текст поста по средствам php функции require():

В общем, здесь фантазия безгранична и правда в том, что невозможность использования php в тексте статьи в некоторых случаях может стать настоящей проблемой. Как-то давно я столкнулся с такой проблемой, решил её взяв и немного переделав код из какого-то плагина (сейчас уже не вспомню название). Итак, чтобы реализовать возможность вставлять исполняемые PHP скрипты в текст статьи / поста или статической страницы, нужно добавить в уже, наверное, до боли знакомый нам файл темы functions.php следующий код:

## Исполняемый PHP код в контенте записи WordPress. ## [exec]PHP_код[/exec] ## ## @version: 1.0 if( 'Исполняемый PHP код в контенте' ) < add_filter( 'the_content', 'content_exec_php', 0 ); function content_exec_php( $content )< return preg_replace_callback( '/\[exec( off)?\](.+?)\[\/exec\]/s', '_content_exec_php', $content ); >function _content_exec_php( $matches )< if( ' off' === $matches[1] )< return "\n\n'. htmlspecialchars( $matches[2] ) .'\n\n"; > else < eval( "ob_start(); ; \$exec_php_out = ob_get_clean();" ); return $exec_php_out; > > >
[exec] // Комментарий global $wp_version; echo "Текущая версия WP: $wp_version"; [/exec]

Чтобы отключить выполнение кода, можно использовать следующую конструкцию. Она выведет просто код, как если бы мы вставили php код как текст.

Важно о защите

Нужно помнить, что этой возможностью может воспользоваться кто угодно, а это огромная дыра в защите, потому что если у кого-либо есть доступ к написанию статей, он легко может сделать с сайтом все что захочет. Чтобы обезопасить себя от возможных пагубных последствий этого хака, можно сделать следующую простую защиту (то что сразу пришло мне в голову): включать исполнение конструкции [exec]php код[/exec] , только в том случае, если, например, у поста есть какое-либо произвольное поле или, скажем, пост написан в 00 минут. Естественно только вы будете знать эту хитрость при которой код будет исполняться и соответственно только вам будет доступна возможность вставить php код в статью. —

Читайте также:  Add folder to path python

Получите много друзей на страницу ВК для того, чтобы сделать ее максимально популярной в сети. Выводите свой аккаунт в топ поиска Контакта с недорогими услугами от представленного сайта. Здесь Вам будут доступны такие ресурсы, как: подписчики в группу, лайки, репосты, просмотры записей и т. д. Успейте сделать максимально выгодную покупку уже сейчас.

До этого из: Код (коддинг)
До этого из: Хуки (хаки сниппеты фильтры события)

Источник

Реализация идеи

1. Создадим php-файл. Я назвал свой «test.php» и добавил его в корневой каталог с загруженной темой, вот сюда:

Должно получится следующим образом:

2. Для использования всех функций WordPress необходимо подключить «wp-load.php», вставляем приведенный ниже код в наш PHP:

require_once $_SERVER["DOCUMENT_ROOT"]."/wp-load.php";

3. Для примера добавляю в php-файл функцию получения временной зоны сайта с выводом на странице:

$timezone = wp_timezone(); echo $timezone->getName();

В итоге мой файл выглядит следующим образом:

В принципе, все готово, теперь можно переходить по ссылке ниже:

https://название_сайта/wp-content/themes/blogshare/test.php

Но блин, какая длинная ссылка получилась, это ведь не удобно! Давайте сократим ссылку и создадим человекоподобный URL (ЧПУ). Например, чтобы страница открывалась по короткому урл:

4. Находим в корневой папке WordPress файл «.htaccess», при помощи которого можно задавать различные настройки сервера apache и открываем его редактором.

5. Добавляем директиву «RewriteRule» после «RewriteBase»:

RewriteRule ^(test)/$ /wp-content/themes/blogshare/test.php [L]

6. Переходим в браузере по заданному URL и видим, что страница отображается и функция отображения часовой зоны работает.

Готово! И никакие плагины не нужны! Естественно существует огромное множество плагинов, чтобы это реализовать, но в них еще нужно разобраться, а можно за несколько шагов, описанных в статье, сделать самому.

Источник

Creating Your First PHP File for WordPress

Rachel McCollin

Rachel McCollin Last updated Mar 20, 2020

In this tutorial and screencast, I’ll show you how to create a PHP file within a WordPress theme. I’ll also show you how to add some PHP code to the file.

This video is taken from my course Learn PHP for WordPress. You can watch the entire course for free here on Envato Tuts+.

WordPress Theme Files

I’ll start by locating the WordPress theme with all of the template files in it. I’ll then create a new page temple file. The purpose of this is to give an alternative way of displaying some of the pages in a site.

Читайте также:  Как удалить скрипты java

The WordPress theme files as shown in Coda

It’s not terribly important what type of file is being created nor what it does. The important thing is how to create a PHP file and add relevant code to it.

Create a New File

Start by creating a new file.

Creating a new file in Coda

The way in which you’d do that may be different depending on what code editor you’re using. I’m using Coda for Mac.

Once the file has been created, give it a name—for example, demo-page.php.

Coda gives it a little flag to denote the fact that it’s a PHP file. But that alone does not mean it will operate as a PHP file—it needs some code. That means an opening PHP tag:

Add Code to the File

Now we can add some code to the file.

Adding code to the file

This is a page template file. That means it requires some commented-out text at the top to tell WordPress what it is and what it’s called.

The first thing to include is a template tag within WordPress to fetch the contents of the header.php file. That’s done by typing get_header .

Whenever you use a function in PHP, you must always include the braces (brackets) after the function name. This is completed with a semicolon.

The braces indicate that it’s a function, and it’s also somewhere that would include any necessary parameters. No parameters are required in this example.

Add a Loop

Adding a loop in the code

Next, add a loop. Again we’ll use a template tag.

if (have_posts() ) : while( have_posts() ) : the_post();

The have_posts template tag lets us know if there are posts to process in the loop. Our loop says, if there are posts to start with, run the the_post() function as long as there are posts remaining.

To output the content to the page requires more template tags and some HTML. I’ll show you how to do that in another tutorial.

We finish off our loop using endwhile and endif .

Another way of writing this loop is by indenting the if and while statements on their own lines with < curly braces. This style is often easier to read, especially if you have to do more coding inside the loop.

There are lots of other things you could add to this loop. If there are posts, you might wish to output a header, for example, or a search bar. You can also use an else statement to handle the case where there are no posts.

Читайте также:  Html convert ascii to

Adding Comments

Adding comments in the code

Multiple line comments in PHP have the slash and then the asterisks. You may use just one asterisk or as many as you want.

It’s useful to do this where there is a new block of code.

Ensure that the slashes are at the beginning and the end: /* and */ . For example, in the functions file, each function has a big section of commented-out text and, with the number of asterisks used, it is very visible.

We can also add single-line PHP comments by starting the comment with // .

Single line PHP comment

So I’ve added an else statement to the loop, to handle the case when there are no posts. Then, I’ve used // to add a comment as a placeholder. Here I’m just using the comment as a reminder to myself, and to anyone reading the code, what is supposed to happen in the else statement.

Experimentation

Experimenting with the code

To experiment with a couple more template tags, add get_sidebar and get_footer to the bottom of the file.

Within a theme template file, those comments fetch the sidebar.php and footer.php files. A reason to do this, instead of just adding the code for a sidebar right in your template, is to ensure those pieces of code only need to be written once in the theme. That way, if you change your sidebar, for example, you don’t have to go back and update every single file in your theme!

With that, you have a bare-bones PHP file within the theme. The main elements required are the opening PHP tags, then the PHP template tags and functions. There may be conditional statements as well. As you can see, the code is indented for readability.

If you follow along with the course, in the next lesson, I’ll show you how to add some HTML to your PHP file.

The Best WordPress Themes and Plugins on Envato Market

Explore thousands of the best WordPress themes ever created on ThemeForest and leading WordPress plugins on CodeCanyon. Purchase these high-quality WordPress themes and plugins, and improve your website experience for you and your visitors.

Here are a few of the best-selling and up-and-coming WordPress themes and plugins available for 2020.

Источник

Оцените статью