Php in post and pages

Insert PHP code In WordPress Page and Post

I want to know the visitor country using PHP and display it in on a WordPress Page. But when I add PHP code to a WordPress page or post it gives me an error. How can we add PHP code on WordPress pages and posts?

 elseif(filter_var($forward, FILTER_VALIDATE_IP)) < $ip = $forward; >else < $ip = $remote; >$ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip)); if($ip_data && $ip_data->geoplugin_countryName != null) < $result = array('ip' =>$ip, 'continentCode' => $ip_data->geoplugin_continentCode, 'countryCode' => $ip_data->geoplugin_countryCode, 'countryName' => $ip_data->geoplugin_countryName, ); > return $result; > $visitor_details = visitor_country(); // Output Country name [Ex: United States] $country = $visitor_details['countryName']; 

4 Answers 4

WordPress does not execute PHP in post/page content by default unless it has a shortcode.

The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.

There are two other «quick and easy» ways to accomplish it without a plugin:

  • Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy — see here: Shortcode API at WP Codex
  • Put it in a template file — make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
Читайте также:  Colin mcrae rally 2005 java

I am using custom theme,I created one page from admin back-end and I want to use different header structure(top part of page) for this page only. I can’t use template file here. I want to do using back-end page only. I put one short code in that set one variable & checked in header.php is that value getting or not? so that depending on that value I will display header.php part which I want for this page. but this variable’s value is getting blank. Please, tell me solution

Источник

How to Insert PHP Code into WordPress Posts and Pages

It’s not a common practice for developers to insert PHP code into WordPress posts and pages. Usually, site owners will modify theme files to create a desired effect. However, some people find placing snippets into posts and pages to be more ideal given certain situations.

If you’re trying to make changes to how a theme behaves, I suggest using a child theme instead of placing PHP in posts. But if you’re looking to include a post or page-specific element with PHP, you can do so with snippets and shortcodes.

Today, I’m going to go over how to place PHP in posts and pages. I still advise making certain changes directly from theme files, but this method works exceptionally well in many instances.

Using PHP Code Snippet

If you’ve tried to insert coding in WordPress, you may notice how it will either strip certain elements or prevent the use altogether. Perhaps one of the best ways to get around this problem is by using PHP Code Snippet.

This plugin will take your snippets of PHP code and turn them into usable shortcodes for WordPress. And because it’s a shortcode, it will work in posts, pages and even the Text widget for a sidebar component.

You can use this to create advertising codes from affiliates, validating logins from users or any other function you might have developed in PHP. Just make sure you’re using a safe and current version of PHP when making modifications.

Install and activate the Insert PHP Code Snippet plugin.

Insert PHP Code Snippet

Setting Up Your Code Snippet

Click the “XYZ PHP Code” function from the left.

XYZ PHP Code

Click the button to “Add New PHP Code Snippet.”

Add New Snippet

Input a Tracking Name for the snippet. This is what the plugin will use to “name” the shortcode. It’s probably better if you keep it short and succinct so you can easily identify it later. It doesn’t have to be anything fancy. For example, you could use the word, “Clock” if you are inserting a PHP coded clock on your site.

Snippet Tracking

PHP Code

Once you are done, click the “Create” button on the bottom.

Click Create

Now, you will see a shortcode created for the code snippet. You can copy and paste this into any area of WordPress that allows the use of shortcodes.

Shortcode

Using PHP in the WordPress Editor

While the shortcode is useful in some situations, what if you don’t want to remember to copy and paste the text? Perhaps you just want to insert PHP in posts from the editor screen.

PHP Code Snippet does that as well. Let me show you where that function is located when creating or editing a post.

Go to Posts and click, “Add New.”

Add New Post

In the visual editor for WordPress, you’ll see a new button. Click the “PHP” from the editor tool bar.

PHP Button

Your list of currently saved PHP code snippets will be visible from this button. Click the snippet you want and the plugin will insert the shortcode automatically.

PHP Snippet

This feature is not available in the Text editor of WordPress. It is available only in the Visual editor for posts, pages and some custom post types. If the button is not available, you’ll have to paste the shortcode yourself.

Customizing Your Website

This method is one of the easiest ways to customize WordPress with PHP code in pages and posts. It’s a simple way to deliver a more engaging experience for visitors. While some PHP adjustments will still require modifying theme files, you can use this plugin to deliver some of the more simpler additions.

What kind of PHP elements do you include in your website design? How often do you modify the files of your themes for specific functions in PHP?

Источник

How do I pass data between pages in PHP?

In a nutshell on «page1.php» I have a calculator that consists of an HTML form, and then the PHP code totals the input and displays the total price. Below the price, it also displays a link to «page2.php» which contains an HTML form where they can enter their contact information. Upon submitting the form the selections they made on «page1.php» in the pricing calculator as well as the contact info on «page2.php» are emailed to me, and they are redirected to the home page. In the email that is submitted to me, I receive the contact info from «page2.php», but I don’t receive anything from «page1.php», so the variables are not getting correctly passed. In addition to the PHP on each page, I am using hidden values in an HTML form on «page2.php» to echo the data that was entered in the HTML form on «page1.php». I know that one of my issues is that I have a couple of $_GET fields when my form is «post». However when I change it so that everything is $_POST , the calculator no longer works. I tried to put this altogether with different snippets of code suggested by others. The form on «page1.php» has 13 fields, named «one» — «thirteen». $total display the values of 1-13.

The second form uses hidden values to echo the info from page1.php, and has three more fields named «name», «email» and «details».

So what would be the correct PHP to put on «page1.php» and «page2.php»? Sorry the code is such a mess, if anyone could point me in the right direction, that would be great.

To add [code] use 4 spaces before each line, and forget the [code] ubb tag. SO uses other formatting. This is your first post so I won’t rate it down, but now you know it 😉

Источник

Allow PHP in Posts and Pages

Плагин Allow PHP in Posts and Pages позволяет исполнять php-код прямо в записях или страницах вашего блога. И в отличие от множества других подобных плагинов, этот плагин умеет удалять разметку, которую автоматически вставляет WordPress, что важно, так как сейчас практически никто не отключает встроенное в движок автоформатирование текста.

Скачиваем плагин по ссылке в конце страницы и устанавливаем его:

2. Копируем папку allow-php-in-posts-and-pages в /wp-content/plugins/.

3. Заходим в админку блога на вкладку «Плагины» и активируем плагин.

Плагин создает свое отдельное меню «Allow PHP in Posts«, состоящее из двух под-меню: «Allow PHP in Posts» и «Information«. По сути, пользоваться настройками вам надо только, если вы будете создавать «сниппеты» кода. Почти все остальное в настройках плагина является справочной информацией.

Сразу после активации плагина вы можете им пользоваться – чтобы вставить php-код в запись достаточно в HTML-режиме редактора обернуть его в теги [php] и [/php]. Объявлять код не надо:

Большинство проблем с плагином может возникнуть из-за встроенного в WordPress автоформатирования текста. Даже справочные примеры php-кода плагина могут не работать по банальной причине – в них используются кавычки (знаки дюйма «), которые WordPress меняет на символы « и ».

Например, если использовать код:

[php] global $user_ID; if($user_ID == 1) { echo "Привет Админ!"; } [/php]
[php] global $user_ID; if($user_ID == 1) < echo "Привет Админ!"; >[/php]

То вы увидите лишь сообщение об ошибке «Parse error«. А единственный недостаток этого кода в использовании в качестве кавычек знаков дюйма. Чтобы понять это, достаточно вставить данный код в дебаг-режиме:

[php debug=1] global $user_ID; if($user_ID == 1) { echo "Привет Админ!"; } [/php]
[php debug=1] global $user_ID; if($user_ID == 1) < echo "Привет Админ!"; >[/php]

Сразу становится ясно, что ошибка возникла из-за замененных WordPress знаков дюйма. При любых проблемах с кодом используйте дебаг-режим вставки кода и ошибки станут очевидны.

Жаль, что плагин автоматом не решает проблему с заменой кавычек. Но зато он удаляет всю разметку, которую автоматически вставляет WordPress – никаких неожиданных переводов строки или абзацев текста. Но как вставить переводы строки или абзацы, если они нужны, но плагин их удаляет? Это просто – достаточно обернуть их в квадратные скобки []. В справочной информации плагина даже есть памятка:

Правда есть одна тонкость — в рассматриваемой версии плагина эта функциональность работает правильно только при включенной опции «Use the old version (pre 2.2.0) code replacement method» в настройках плагина.

Таким образом, плагин заменяет квадратные скобки на угловые. Но что делать, если вам необходимо использовать квадратные скобки в коде? Достаточно их экранировать через символ \, то есть так:

В плагине реализована возможность создания «сниппетов» кода. Зайдите в «Allow PHP in Posts\Code Snippets» — тут вы можете создавать и редактировать сниппеты c php-кодом. Это может быть полезно, если вы часто используете один и тот же php-код в ваших записях. Например, создадим сниппет под именем «Hello» со следующим кодом:

Использовать данный сниппет можно нажав на кнопку «Allow PHP» в визуальном редакторе и указав его номер.

Можно также просто вставить нужный сниппет через шорткод [php function=2], где 2 это номер сниппета.

Плагин поддерживает вставку php-кода и в текстовых виджетах:

Плагин не лишен недостатков – одна только запутанная система справки чего стоит, но это единственный подобный плагин, который умеет удалять вставленную WordPress разметку, не удаляя ее вообще из всей записи.

Информация о плагине в репозитории wordpress.org не найдена. Или wordpress.org в данный момент недоступен или плагин был временно удален из репозитория (например, из-за найденной критической ошибки в плагине). Попробуйте найти плагин в репозитории вручную.

Понравился пост? Подпишись на обновления по RSS или Twitter !

Да, в html-редакторе… Вставил Ваш код и ошибка… Пришёл к выводу, что может быть тема не поддерживает php? Кстати в опциях «Allow PHP in Post and Pages» надо что – то менять? У меня там везде «No:» выбрано…

просто уточнить — в редакторе две вкладки, визуально и текст — вставлять надо во вкладке текст, иначе вордпресс кавычки испортит. второе, не знаю про опции — я с опциями по умолчанию играюсь, у меня там Yes стоит на «Use the old (pre 2.2) code replacement method». попробуйте.

У меня «визуальный редактор» отключен в настройках WP… Потому у меня только html-редактор доступен…
Пришлось остановиться на плагине Tagnetic Poetry…

попробуйте на дефолтном шаблоне с отключенными остальными плагинами. просто интересно, откуда взялась эта ошибка — на тестовом сервере я просто ну никак не могу ее повторить, у меня все работает как часы.

Источник

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