问题
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