WordPress add php function

Insert PHP code in WordPress

Since it is not possible to wright PHP code directly into WordPress articles or pages, we put this code inside the functions.php file and use WordPress hooks to place it on the pages and locations we want.

In the WordPress dashboard, go to Appearance ➡ Theme File Editor and copy the following code into the theme’s functions.php file.

Please create a child theme for your main theme, otherwise all your customization in functions.php will be lost after each update.
Create child theme in WordPress step by step [without plugin]

In this tutorial, we will use the following PHP code, this code prints a sample message on page. To insert this code in WordPress, we use WordPress hooks and Conditional Tags.

// code1 // A simple PHP code that print a h5 tag with some styling. echo ' 
This message is generated by my own PHP code.
.promo
';

Insert PHP code in WordPress frontend

To insert code in WordPress Front end, we use init hook and is_admin() conditional tags.

// Snippet code in WordPress front-end add_action( 'init', 'frontEndFunction' ); function frontEndFunction() < if(!is_admin()) < // Your php code here or use code1 for testing. >>

insert code in WordPress front end

In this case, our PHP code is displayed on all WordPress front-end pages.

Insert PHP code in WordPress backend

If you want to insert your PHP code in WordPress backend pages, in the above code use “is_admin()” instead of “!is_admin()”.

// Snippet code in WordPress backend add_action( 'init', 'backEndFunction' ); function backEndFunction() < if(is_admin()) < // Your php code here. >>

Insert PHP code in WordPress Head

To insert code in WordPress head, we use wp_head hook.

// Snippet code in WordPress header add_action('wp_head', 'your_function_name'); function your_function_name()< // Your php code here. >;

Insert script in WordPress Head

To insert scripts such as Google Analytics or other scripts, first close the PHP tag with ?> and enter the script or HTML code, then open the PHP tag again with

// insert script or Html in WordPress header add_action('wp_head', 'your_function_name'); function your_function_name() < ?>// Put your script or Html code here ;

Enqueue scripts and styles in WordPress

If you want to enqueue .js or .css file to WordPress, use the following method.
Enqueue both scripts and styles from a single action hook.

/** * Proper way to enqueue scripts and styles. */ function wpdocs_theme_name_scripts() < wp_enqueue_style( 'style-name', get_stylesheet_uri() ); wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true ); >add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

Insert PHP code in WordPress Body tag

To insert code in opening body tag, we use wp_body_open() hook.

// Snippet code in opening body tag add_action('wp_body_open', 'your_function_name'); function your_function_name()< // Your php code here. >

To insert code in WordPress header, we use wp_footer hook.

// Snippet code in WordPress footer add_action('wp_footer', 'your_function_name'); function your_function_name()< // Your php code here. >

insert PHP code in WordPress footer

To insert scripts such as Google Analytics or other scripts in wordpress footer, first close the PHP tag with ?> and enter the script or HTML code, then open the PHP tag again with

// insert script or Html in WordPress footer add_action('wp_footer', 'your_function_name'); function your_function_name() < ?>// Put your script or Html code here 

Insert PHP code in WordPress For Only Specific Pages

We use Conditional Tags to insert PHP code on specific pages.
We recommend that you visit the official WordPress site to learn more about this. Here we briefly review the most important Conditional Tags.

Читайте также:  Nav navbar nav css

First you need to learn how to get page IDs in WordPress.
To do this, go to the Articles or Pages page in the WordPress admin dashboard and hold the mouse on the page you want, the ID of that page will be displayed in the link at the bottom left corner of the screen.

get wordpress pages ID

For example, in the image above, the ID of page is 486 .

Insert PHP code in single posts

Now, if you want to insert PHP code only in site articles, you must use the following method:

// Snippet code in WordPress posts add_action( 'wp_body_open', 'your_function_name'); function your_function_name()< if ( is_single( ) ) < // Your php code here. > >

Insert PHP code in Category Pages

is_category(): all category pages
is_category( ’17’ ): Category with ID number 17
is_category( ‘tutorial’ ): Category with “tutorial” Slug
is_category( array( 17, ‘tutorial‘ ) ): Category ID 17 or the Category Slug is “tutorial”

Insert PHP code in Tag Pages

is_tag(): all tag pages
is_tag( ‘4’ ): tag page with ID number 4
is_tag( ‘joomla’ ): tag page with “joomla” Slug
is_tag( array( 4, ‘joomla‘ ) ): tag page with ID 4 or the tag Slug is “joomla”

get Tag ID and Slug in WordPress

// Snippet code in WordPress tag pages add_action( 'wp_head', 'your_function_name'); function your_function_name() < if ( is_tag() ) < // Your php code here. > >

Insert PHP code in Woocommerce Product Pages

// Snippet code in Woocommerce product pages add_action( 'wp_head', 'your_function_name'); function your_function_name()< if ( is_product() ) < // Your php code here. > >

Insert PHP code in Woocommerce Product Category Pages

is_product_category(): all Woocommerce product Category pages
is_product_category( ‘4’ ): Woocommerce product Category page with ID number 4
is_product_category( ‘shirt’ ): Woocommerce product Category page with “shirt” Slug
is_product_category( array( 4, ‘shirt‘ ) ): Woocommerce product Category page with ID 4 or the Slug is “shirt”

Читайте также:  Что такое gui java

get Woocommerce product category ID and Slug in WordPress

// Snippet code in Woocommerce product Category pages add_action( 'wp_head', 'your_function_name'); function your_function_name()< if ( is_product_category() ) < // Your php code here. > >

Insert PHP code in Woocommerce Product Tag Pages

is_product_tag(): all Woocommerce product tag pages
is_product_tag( ‘4’ ): Woocommerce product tag page with ID number 4
is_product_tag( ‘fantasy-mug’ ): Woocommerce product tag page with “fantasy-mug” Slug
is_product_tag( array( 4, ‘fantasy-mug‘ ) ): Woocommerce product tag page with ID 4 or the Slug is “fantasy-mug”

// Snippet code in Woocommerce product tag pages add_action( 'wp_head', 'your_function_name'); function your_function_name()< if ( is_product_tag() ) < // Your php code here. > >

Insert PHP code in Pages with given terms

Check if the current post has any of given terms. It expects a taxonomy slug/name as a second parameter.
has_term( array( ‘green’, ‘orange’, ‘blue’ ), ‘color’ ): Will return all the things (products) that has green, orange or blue colors.

For example, if we want to insert our code on the Woocommerce product pages that are in category nose-ring or ring, we use the following code.

Wordpress Conditional Tags with taxonomy

// Snippet code in Woocommerce product pages that are in ring or nose-ring category add_action( 'wp_body_open', 'your_function_name'); function your_function_name()< if ( is_product_tag() && has_term( array( 'ring', 'nose-ring' ), 'product_cat' ) ) < // Your php code here. // echo '

Sorry, nose rings and rings are currently unavailable in the store.

';
> >

WordPress has many more hooks that you can use, but we did not name them in this article, we recommend that you visit the WordPress site and read more about it.

If this article is difficult for you to read in text, you can watch the video version below.

Источник

Как правильно добавить PHP код на страницу WordPress?

Вопрос 1.
Есть необходимость размещения различного PHP — кода в приличном количестве страниц WordPress.
До сих пор делал это создавая для каждой страницы свой шаблон и выбирая его при создании соответствующей страницы в WordPress, таким образом уже собралось штук 20 шаблонов, используемых по одному разу.
Есть ощущение, что это неверный подход. Если прав, то как правильно решать такую задачу?

Вопрос 2.
Есть отдельная PHP HTML страница, на которой хочется использовать функции WordPress, например wp_get_current_user(). Как это сделать?

deniscopro

1. Смотря что и где и как. Например, с помощью get_template_part подключить файл, прописать в нем условия и код. Или сделать свой тег шаблона или свой шорткод или виджет или произвольные поля задействовать.
Но и шаблоны тоже можно вполне использовать. Хотя опять же, если формализовать что у Вас там вставляется, возможно, удастся уменьшить и их количество.

Читайте также:  Меняем фон сайта с помощью HTML - Нубекс

2. Нужно подключить wp-load.php
require_once(«/path/wp-load.php»);

Все, разобрался, был разлогинен.) Спасибо.

А не подскажете, в чем может быть дело? Создал файл

deniscopro

require_once("../wp-load.php"); add_action( 'plugins_loaded', 'get_user_info' ); function get_user_info()< $current_user = wp_get_current_user(); echo 'User display name: ' . $current_user->display_name . '
'; >

P.S. Лучше для разных задач создавать разные вопросы, а то свалка получается.

На сколько безопасно использовать следующий метод?
Добавляем в файл «functions.php» темы такую функцию:

/* чтобы вставить код php в статьях/страницах WordPress, поставьте шоркод: [exec]код[/exec] */ function exec_php($matches) < eval('ob_start();'.$matches[1].'$inline_execute_output = ob_get_contents();ob_end_clean();'); return $inline_execute_output; >function inline_php($content) < $content = preg_replace_callback('/\[exec\]((.|\n)*?)\[\/exec\]/', 'exec_php', $content); $content = preg_replace('/\[exec off\]((.|\n)*?)\[\/exec\]/', '$1', $content); return $content; >add_filter('the_content', 'inline_php', 0);

https://wordpress.org/plugins/exec-php/
Неплохой плагин, позволяющий вставлять php-код прямо в текстовый редактор страницы.

Azat2015: поиском вы не пользуетесь принципиально? Есть куча аналогов.
https://wordpress.org/plugins/insert-php/

Войдите, чтобы написать ответ

Как сделать миниатюру в woocommerce фоном?

Источник

🌐 Как добавить PHP-код в запись или страницу WordPress

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

Причины добавить PHP-код в запись или страницу WordPress

По умолчанию WordPress не позволяет запускать PHP-код в сообщениях или на страницах.

Рекомендуемый способ добавления функций PHP – изменение дочерней темы или создание собственных шаблонов страниц.

Несмотря на это, бывают случаи, когда вы можете захотеть добавить определенные функции PHP к отдельному сообщению или странице.

В этих случаях вы можете переопределить правило, используя плагины виджетов кода WordPress.

Следующее руководство покажем вам процесс использования плагина Insert PHP Code Snippet для добавления PHP-кода непосредственно в сообщение или страницу WordPress.

Как добавить PHP-код в сообщение или страницу WordPress с помощью плагина

Прежде чем углубиться в руководство, убедитесь, что вы установили и активировали плагин Insert PHP Code Snippet.

На панели управления WordPress перейдите в раздел XYZ PHP Code -> PHPCode Snippets.

На странице «PHP Code Snippets» нажмите «Add New PHP Code Snippet». Добавьте желаемую функцию PHP и ее имя отслеживания в соответствующие поля. Затем щелкните “Create” .

Если процесс прошел успешно, на экране появится подтверждающее сообщение и новая функция.

Для будущего использования убедитесь, что все функции PHP, которые вы хотите использовать, активны, проверив раздел «Action».

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

Чтобы добавить PHP-код в запись или страницу WordPress, вставьте шорткод фрагмента функции, которую вы хотите использовать, в нужное место.

Если вы используете редактор блоков Гутенберга, используйте шорткод или блок кода для его отображения.

Заключение

Просто потому, что WordPress не позволяет запускать PHP-код в записи или на странице, это не невозможно.

Используя плагины виджетов кода WordPress, вы можете легко добавлять различные функции PHP к своим сообщениям или страницам.

Источник

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