我在functions.php中具有功能
function my_function() {
//do something
}
但是在此函数内部,我需要检查页面模板,并且需要使用is_page()或is_home(),但在functions.php中,此方法无效。
我可以在header.php中检查页面模板,例如:
if (is_page(7)) :
$myVariable = 1;
else :
$myVariable = 2;
endif;
最后,它可以在header.php中工作,但是现在在my_function中的functions.php中,我需要这样的东西:
function my_function(){
if($myVariable == 1) :
//do something
else :
//do something else
endif;
}
我不知道如何传递此变量,或者如何检查函数中的页面模板。
答案 0 :(得分:0)
您可以按如下方式使用全局关键字。
if (is_page(7)) :
$myVariable = 1;
else :
$myVariable = 2;
endif;
function my_function(){
global $myVariable;
if($myVariable == 1) :
//do something
else :
//do something else
endif;
}
答案 1 :(得分:0)
您可以像这样将变量作为参数传递给函数:
<div>
<strong>Current lat: </strong> {{ profile.latitude }}<br/>
<strong>Current long: </strong> {{ profile.longitude }}<br/><br/>
</div>
<label for="locations-status">Locations enabled?</label>
<input type="checkbox" id="locations-status">
<script
src="https://code.jquery.com/jquery-3.4.0.min.js"
integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
crossorigin="anonymous"></script>
<script>
var PROFILE_ID = {{ profile.id }};
</script>
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
getLocation()
}
else if($(this).prop("checked") == false){
console.log("Location services are disabled");
}
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
console.log("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
var latlon = (position.coords.latitude + ','+ position.coords.longitude);
$.post({
url: "{% url 'profile-detail' profile.id %}",
data: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
}
});
console.log(latlon);
};
</script>
或者您可以像这样声明function my_function($myVariable) {
if($myVariable == 1) :
//do something
else :
//do something else
endif;
}
作为全局变量:
$myVariable