Wordpress - Safest method to define global variables

狂风中的少年 提交于 2019-12-22 01:13:18

问题


I don't know if "global" is the right word, but what I have to do is: define a variable that I can use in many parts of the template.

Example: I have to define a variable that contains the ID of a static page

$page_id = 34

and I have to use it in different template parts, with functions like

get_page_link($page_id)

I found many way to do it (PHP define(), in function.php, global, ...) but I ask what is the most secure, in your opinion.


回答1:


You can either define it in wp-config file (which will be accessible among all theme ) or in your function.php of your theme directory.

Example: Function.php

global $blog_pageId;
$blog_pageId = 34;

Or just create a small function which return you the id.

function get_blog_page_id(){
      return "34";
}

Than one can call it as,

 $blog_pageId = get_blog_page_id();



回答2:


You can also use wordpress default functionality like

global $wpdb;

on above global variable $wpdb is use in all page of wordpress so you can also create your own function and create one global variable which is declare all pages or posts .




回答3:


if you're using pretty permalinks, get_query_var('page_id') won't work.

Instead, get the queried object ID from the global $wp_query:

// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id     = get_queried_object_id();


// "Dirty" pre 3.1
global $wp_query;

$page_object = $wp_query->get_queried_object();
$page_id     = $wp_query->get_queried_object_id();


来源:https://stackoverflow.com/questions/16233720/wordpress-safest-method-to-define-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!