모든 WordPress 페이지에서 변수를 사용하는 가장 좋은 방법
저는 여러 가지 변수가 있는 커스텀 테마를 만들고 있습니다.
예를 들어:
$tv = $options['tv'];
$movies = $options['movies'];
$print = $options['print'];
//....and about 50 more.
이 목적을 위해 저는 그것들을 모두 vars.php라는 파일에 넣은 다음 헤더에 넣었습니다.php는 내가 포함시킨 테마의...
require_once('vars.php');
이게 먹히긴 하지만 최선의 방법은 아닌 것 같아요.글로벌 변수(아마도 functions.php)를 사용하는 것은 좋지 않다고 여러 번 읽었습니다만, 이것이 사실입니까?
그러나 functions.php(많은 변수라도)에서 글로벌 변수를 사용해도 괜찮다면, 이것이 올바른 방법입니까?
global $tv;
$tv = $options['tv'];
global $movies
$movies = $options['movies'];
global $print
$print = $options['print'];
이를 위한 최선의 방법은 함수에 모든 변수를 명시적으로 정의하는 것입니다.php 또는 플러그인의 메인 플러그인 파일에 있습니다.이것이 akismet을 포함한 가장 인기 있는 플러그인임을 확인했습니다.특히 이 작업을 수행해야 합니다.
define( MYVAR_TV, $options['tv'] );
define( MYVAR_MOVIES, $options['movies'] );
define( MYVAR_PRINT, $options['print'] );
이 후에 원하는 곳에 사용하시면 됩니다.
echo MYVAR_TV;
도움이 됐으면 좋겠다.
글로벌하게 사용하는 것은 좋지만 권장되지는 않습니다(자세한 내용은 여기를 참조하십시오). PHP의 글로벌 변수는 나쁜 관행으로 간주됩니까? 그렇다면 왜?)싱글톤의 실장을 검토할 수 있습니다.
<?php
class GlobalVariable {
/**
* @var array
*/
public static $option = [];
}
// You can set the variable using this way
GlobalVariable::$option['movies'] = 1;
// And get the variables using that array
print_r(GlobalVariable::$option);
이게 도움이 되길 바라.
함수에서 함수를 만드는 것은 어떨까요?변수 배열을 반환하는 php?
" " " 입니다.$options = get_my_custom_vars();
글로벌 변수를 원하는 경우 모든 변수를 포함하는 배열이 만들어집니다.사용방법:
$GLOBALS['your-varriable']
저는 개인적으로 Acf Options Addon을 사용하는 것을 좋아합니다.이를 변경하여 wpml 플러그인을 통해 번역할 수 있도록 하는 것도 도움이 됩니다.
이러한 옵션은 백엔드의 "옵션 페이지" 내에서 또는 링크의 설명에 따라 추가/편집할 수 있습니다.
기능을 통해 애드온을 초기화한 후.php
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
를 통해 템플릿에 있는 이들을 호출하기만 하면 됩니다.
<?php the_field('header_title', 'option'); ?>
- 이러한 예는, 「Acf Options Page」의 메뉴얼에서 발췌한 것입니다.
- 이것을 실행하려면 , https://www.advancedcustomfields.com/ 가 인스톨 되어 있을 필요가 있습니다.
커스텀 스트림 래퍼도 구현할 수 있습니다.에 필요한 할 수 있습니다.file_get_contents,file_put_contents,fread,fwrite파일을 읽고 쓰거나 리모트 URL에서 정보를 얻는 것과 같습니다.
실제로 PHP 매뉴얼에는 요청하신 글로벌 변수를 사용한 예가 있습니다.그러나 WP의 사용 사례와 사용 예에 맞게 완성도 순으로 추출해 보겠습니다.
<?php
// variable-stream-class.php just this is pulled from the PHP manual
class VariableStream {
var $position;
var $varname;
function stream_open($path, $mode, $options, &$opened_path)
{
$url = parse_url($path);
$this->varname = $url["host"];
$this->position = 0;
return true;
}
function stream_read($count)
{
$ret = substr($GLOBALS[$this->varname], $this->position, $count);
$this->position += strlen($ret);
return $ret;
}
function stream_write($data)
{
$left = substr($GLOBALS[$this->varname], 0, $this->position);
$right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
$GLOBALS[$this->varname] = $left . $data . $right;
$this->position += strlen($data);
return strlen($data);
}
function stream_tell()
{
return $this->position;
}
function stream_eof()
{
return $this->position >= strlen($GLOBALS[$this->varname]);
}
function stream_seek($offset, $whence)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
$this->position = $offset;
return true;
} else {
return false;
}
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
} else {
return false;
}
break;
case SEEK_END:
if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
$this->position = strlen($GLOBALS[$this->varname]) + $offset;
return true;
} else {
return false;
}
break;
default:
return false;
}
}
function stream_metadata($path, $option, $var)
{
if($option == STREAM_META_TOUCH) {
$url = parse_url($path);
$varname = $url["host"];
if(!isset($GLOBALS[$varname])) {
$GLOBALS[$varname] = '';
}
return true;
}
return false;
}
}
기능을 분리하는 플러그인이 있어 디버깅을 위해 비활성화할 수 있고 활성 테마를 변경해도 손실되지 않는다고 가정합니다.플러그인의 엔트리 포인트에 다음과 같은 것을 넣는 것을 추천합니다.
<?php
/**
* Plugin Name: Stream Wrapper for global variables
* Plugin URI: https://stackoverflow.com/q/46248656/
* Description: Utility class and functions to enable global data sharing in WordPress
* Author: Jesús E. Franco Martínez and the PHP Documentation Group
* Contributors: tzkmx
* Version: 0.1
* Author URI: https://tzkmx.wordpress.com
*/
require 'variable-stream-class.php';
stream_wrapper_register("var", "VariableStream")
or wp_die("Failed to register protocol", null, ['back_link' => true]);
그런 다음 템플릿 또는 기타 사이트 플러그인에서 위에서 언급한 기능을 사용하거나 사용자 지정 별칭을 사용할 수 있습니다.요청에 따라 확장하겠습니다.
// functions.php in your theme or better, in the same plugin.php above
// Using a hook just for frontend in order to get populated
// our variables without require calls in the theme.
add_action('wp_head', 'populate_my_awesome_plugin_options');
function populate_my_awesome_plugin_options() {
// Let's say you get your data from a single get_option call
$options = get_option( 'my_awesome_plugin_options' );
foreach( $options as $key => $value ) {
file_put_contents( 'var://' . $key, $value );
}
}
function pop_get_var( $var_name ) {
return file_get_contents( 'var://' . $var_name );
}
마지막으로 헤더에 있습니다.php 등의 템플릿파일을 사용하여 데이터를 소비합니다.콜은 다음과 같습니다.
<p>TV favorite show: <strong><?= pop_get_var( 'tv' ) ?></strong></p>
<p>Movies I like: <strong><?= pop_get_var( 'movies' ) ?></strong></p>
<p>Impressum: <em><?= pop_get_var( 'print' ) ?></em></p>
처음에는 많은 보일러 플레이트처럼 보일 수 있지만, 우려 사항의 분리 때문에 상수를 사용하는 것과 같은 스칼라 값에만 국한되지 않고 스트림 래퍼를 원하는 데이터 저장소에 대한 어댑터로 사용할 수 있으며 메모리에 저장하거나 WordPress 옵션 테이블에 저장할 수도 있습니다.커스텀 기능을 사용하면 싱글톤 클래스에 이렇게 긴 콜을 작성하거나 커스텀 데이터에 액세스 하고 싶은 장소에서 글로벌하게 콜을 발신하는 번거로움이 없어집니다.
실제로 PHP 매뉴얼의 예를 읽으면 호출할 수 있는 전체 텍스트를 저장하기 위해 래퍼를 사용하는 예를 볼 수 있습니다.include시리얼화된 데이터도 사용할 수 있습니다.예를 들어,json_encode/json_decode래퍼와 함께 저장하여 데이터베이스에 직접 저장할 수 있습니다.PDO를 사용하여 데이터베이스에서 데이터를 쓰고 읽는 다른 예도 있지만 WordPress를 사용하도록 쉽게 포팅할 수 있습니다.$wpdb물건.
언급URL : https://stackoverflow.com/questions/46248656/the-best-way-to-use-variables-on-all-wordpress-pages
'programing' 카테고리의 다른 글
| Swagger 2.x를 사용하는 동안 HATEOAS가 Spring-Boot 버전 >= 2.2.x에 대해 문제를 일으키기 시작하는 이유는 무엇입니까? (0) | 2023.03.25 |
|---|---|
| Oracle - 읽기 전용 사용자 생성 방법 (0) | 2023.03.25 |
| AngularJS - ng-Repeat 내의 속성 이름을 참조하려면 어떻게 해야 합니까? (0) | 2023.03.25 |
| express/node js에서 오류 http 응답을 보내는 방법 (0) | 2023.03.25 |
| 타이프스크립트:사용자 지정 유형에 대해 "type of" 확인 (0) | 2023.03.25 |