In my wordpress website I getting below error
Fatal error: Call to a member function get_id() on boolean in /home/customer/www/ae.testing.com/public_html/wp-content/themes/movedo-child/functions.php on line 33
Previously working fine . but now what exact issue i am not getting. if any one have idea then let me know
function.php as follows:
<?php
function movedo_child_theme_setup() {
}
add_action( 'after_setup_theme', 'movedo_child_theme_setup' );
function display_price_in_variation_option_name( $term ) {
echo $product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach($product_variations as $variation){
if(count($variation['attributes']) > 1){
return $term;
}
foreach($variation['attributes'] as $key => $slug){
if("attribute_" == mb_substr( $key, 0, 10 )){
$taxonomy = mb_substr( $key, 10 ) ;
$attribute = get_term_by('slug', $slug, $taxonomy);
if($attribute->name == $term){
$term .= " (" . wp_kses( wc_price($variation['display_price']), array()) . ")";
}
}
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
On line «$id = $product->get_id();» I m getting this error.
asked Jun 7, 2021 at 14:34
The issue seems quite simple, you are hooking into ‘after_setup_theme’ which is fired for every single wordpress request. In this context you are supposing you always have a product in the main query context which is not always true.
To simply shut the error wrap $id = $product->get_id(); into an if like this:
if(!empty($product)){
$id = $product->get_id();
}
...
But to really make it bullet proof you should ask yourself when you really want to look into wc_get_product to get the current product. I’m assuming you may want that only on the product detail page.
Since you are hooking into ‘after_setup_theme’ conditional tags can be used.
Change your code to bail out as soon as it is not executed in the right page doing something like this:
function display_price_in_variation_option_name( $term ) {
if (!is_product()){
return;
}
echo $product = wc_get_product();
$id = $product->get_id();
...
answered Jun 7, 2021 at 15:09
DiegoDiego
1,5761 gold badge13 silver badges26 bronze badges
Wc_get_product is returning false somehow.
Try
global $product; //
![]()
answered Jun 7, 2021 at 16:07
|
Хитрый Лис 3 / 3 / 2 Регистрация: 17.04.2014 Сообщений: 37 |
||||||||
|
1 |
||||||||
|
09.06.2014, 13:07. Показов 3968. Ответов 7 Метки нет (Все метки)
Здравствуйте. Тут такая ситуация. Вот как всё выглядит в index.php:
А вот log.php:
Может, потому что log.php вставляется в index.php? По-моему, это полный бред. Но всё может быть. Помогите, пожалуйста.
__________________
0 |
|
Para bellum
5735 / 4122 / 1500 Регистрация: 06.01.2011 Сообщений: 11,251 |
||||||||||||
|
09.06.2014, 15:52 |
2 |
|||||||||||
|
Решение
В index.php и post.php массив $_GET[‘id’] работает. В log.php нет А как Вы определили, что он не работает? Сделайте:
Может Вы просто не передаёте туда значение?
Надо так:
Добавлено через 4 минуты
1 |
|
Хитрый Лис 3 / 3 / 2 Регистрация: 17.04.2014 Сообщений: 37 |
||||||||
|
09.06.2014, 16:33 [ТС] |
3 |
|||||||
|
lyod, определил, что не работает, когда делал в log.php вот так:
Переносил на ошибку 404. То есть. Дело не в log.php, а в index.php, т.к. когда я пишу запрос в адресной строке: …../log.php?id=1 Открывается файл, и в нём прекрасно отображаются сообщения. …../index.php?id=1 log.php?id=1 внутри него не отображается, а отображается просто log.php, из-за чего и срабатывает скрипт выше. Значит, действительно, значение не передаётся. Но почему? Вроде всё прописал…
0 |
|
Para bellum
5735 / 4122 / 1500 Регистрация: 06.01.2011 Сообщений: 11,251 |
||||||||||||
|
09.06.2014, 16:53 |
4 |
|||||||||||
|
Решение А, то есть Вы хотите передать параметр, открывая файл log.php с помощью fopen? Я только заметил… Так сделать не получится
Или можно с помощью file_get_contents либо curl. Но вообще, зачем такое понадобилось? Добавлено через 1 минуту Не по теме: И, вот это что?
Лучше так:
1 |
|
3 / 3 / 2 Регистрация: 17.04.2014 Сообщений: 37 |
|
|
09.06.2014, 17:59 [ТС] |
5 |
|
lyod, попробовал сделать полный адрес http — то же самое выходит.
0 |
|
5735 / 4122 / 1500 Регистрация: 06.01.2011 Сообщений: 11,251 |
|
|
09.06.2014, 19:07 |
6 |
|
Я хочу, чтобы размер окна чата не менялся, сколько бы не было сообщений Я не понял
1 |
|
3 / 3 / 2 Регистрация: 17.04.2014 Сообщений: 37 |
|
|
10.06.2014, 14:38 [ТС] |
7 |
|
lyod, а… ну хорошо, допустим… Я заменил fopen на include, но он не берёт url с get-запросом. Пробовал и полный адрес http прописывать, и просто так. Всё равно выдаёт ошибку, что не нашёл файл. Видимо с fopen была та же ситуация. Может есть такая функция, которая подключает веб-страницу по url, в котором содержится get-запрос? Добавлено через 59 минут
0 |
|
5735 / 4122 / 1500 Регистрация: 06.01.2011 Сообщений: 11,251 |
|
|
11.06.2014, 08:50 |
8 |
|
Пожалуйста, конечно, но мне кажется использовать GET в данном случае не самый удачный вариант… Тут можно сделать по-другому, только я не знаю, почему Вам нужно передавать параметр в подключаемый файл.
0 |
За последние 24 часа нас посетили 8757 программистов и 850 роботов. Сейчас ищут 409 программистов …
-

Drobotko Taras
Активный пользователь- С нами с:
- 13 окт 2016
- Сообщения:
- 30
- Симпатии:
- 1
Добрый день! Пишу код для edit.php (используя PDO), который дает возможность админу редактировать статьи на блоге. Админ заходит с главной страницы, например, по адресу /edit.php?id=7, делает необходимые правки статьи в полях формы и жмет кнопку «Сохранить». Но! Необходимого обновления таблицы в БД mysql не происходит. Проанализировав код, я пришёл к заключению, что ошибка св’язана с передачей $_GET[‘id’] внутрь блока if (isset($_POST[‘submit’])) { …}. $_GET[‘id’] передает id статьи, по которому идентификуется стаття в БД. Как, в моем случае, можно передать id статьи внутрь блока с кодом:
-
if (isset($_POST[‘submit’])) {
-
$stmt = $conn->prepare(‘UPDATE content SET title= :title, short_desc= :short_desc,
-
full_desc= :full_desc, timestamp= :timestamp WHERE id = :id’);
-
$stmt->bindParam(‘:id’, $_GET[‘id’], PDO::PARAM_INT);
-
$stmt->bindParam(‘:title’, strip_tags($_POST[‘title’]));
-
$date = «{$_POST[‘date’]} {$_POST[‘time’]}«;
-
$stmt->bindParam(‘:timestamp’, strtotime($date));
-
$status= $stmt->execute();
-
} catch(PDOException $e) {
-
print «ERROR: {$e->getMessage()}»;
-
require(‘base/footer.php’);
-
<form action=»<?php print $_SERVER[«PHP_SELF»]; ?>» method=»POST»>’
Помогите, пожалуста, разобраться!
-
-

Drobotko Taras
Активный пользователь- С нами с:
- 13 окт 2016
- Сообщения:
- 30
- Симпатии:
- 1
-
<form action=»<?php print $_SERVER[«PHP_SELF»]; ?>» method=»POST»>
-
<label for=»title»>Заголовок</label>
-
<input type=»text» name=»title» id=»title» required maxlength=»255″ value=»<?php echo $article[‘title’]; ?>«>
-
<label for=»short_desc»>Короткий зміст</label>
-
<textarea name=»short_desc» id=»short_desc» required maxlength=»600″><?php echo $article[‘short_desc’]; ?></textarea>
-
<label for=»full_desc»>Повний зміст</label>
-
<textarea name=»full_desc» id=»full_desc»
-
required><?php echo $article[‘full_desc’]; ?></textarea>
-
<label for=»date»>День створення</label>
-
<input type=»date» name=»date» id=»date» required
-
value=»<?php print date(‘Y-m-d’, $article[‘timestamp’]); ?>«>
-
<label for=»time»>Час створення</label>
-
<input type=»time» name=»time» id=»time» required
-
value=»<?php print date(‘G:i’, $article[‘timestamp’]); ?>«>
-
<input type=»submit» name=»submit» value=»Зберегти»>
-
-
<form action=»<?php print $_SERVER[«PHP_SELF»].’?id=7′; ?>
так надо гет то оптравлять
-
-

Maputo
Активный пользователь- С нами с:
- 30 июл 2015
- Сообщения:
- 1.136
- Симпатии:
- 173
-
<?php print $_SERVER[«REQUEST_URI»]; ?>
Describe the Bug
When i want use the get_id of CameraRecognitionObject when using Python, it occurs the error that the get_id are not in the list, i wonder how could i take the id or the position out?

Screenshots
If applicable, add screenshots to help explain your problem.
System
- Operating System: macOS Mojave
You should write:
if data.get_id() == 1813:
You should write:
if data.get_id() == 1813:
it still occur the error
[recog] Traceback (most recent call last):
[recog] File «recog.py», line 43, in
[recog] if data.get_id() == 1803:
[recog] AttributeError: ‘list’ object has no attribute ‘get_id’
Can you please post your complete controller source code?
Can you please post your complete controller source code?
from so far it is like from controller import Robot from controller import Camera from controller import CameraRecognitionObject TIME_STEP = 64 robot = Robot() camera1=Camera('camera1') camera1.enable(TIME_STEP) camera1.recognitionEnable(TIME_STEP) wheels = [] data=[] wheelsNames = ['wheel1', 'wheel2', 'wheel3', 'wheel4'] for i in range(4): wheels.append(robot.getMotor(wheelsNames[i])) wheels[i].setPosition(float('inf')) wheels[i].setVelocity(0.0) while robot.step(timestep) != -1: leftSpeed = 0.0 rightSpeed = 0.0 cameraData = camera1.getImage() number = camera1.getRecognitionNumberOfObjects() data = camera1.getRecognitionObjects() for i in range(number): if data.get_id() == 1803: leftSpeed = 6.0 rightSpeed = 6.0 if((data.get_position())> -3): leftSpeed = 0.0 rightSpeed = 0.0
Can you try this:
[...]
data = camera1.getRecognitionObjects()
for d in data:
if d.get_id() == 1803:
[...]
Can you try this:
[...] data = camera1.getRecognitionObjects() for d in data: if d.get_id() == 1803: [...]
My aim is to scan all the objects in the image to check whether there exist the ideal id(which we have test and record before). Once confirmed, I want to get the z, x or y position of the object. ( for the next step). However, when I take use of python, I do not understand how to call database.
- Do I need to use the CameraRecognitionObject API?
Such as directly use
CameraRecognitionObject.get_id()
or use
data = camera1.getRecognitionObjects()
and use data.get_id() - how to call the position, do i need to built another 3 length array like
position =[3]
position=data[i].get_position()
and take use of position[2] to use the z-position?
and how could i know the objects’ id
is the class more like
data[i].get_position[k](in C language)?
how to write it in python?
Thanks a lot.
Yes, getRecognitionObjects() returns an array of CameraRecognitionObject which you can access using either the []operator or the for object in objects construct which I originally suggested.
Describe the Bug
When i want use the get_id of CameraRecognitionObject when using Python, it occurs the error that the get_id are not in the list, i wonder how could i take the id or the position out?

Screenshots
If applicable, add screenshots to help explain your problem.
System
- Operating System: macOS Mojave
You should write:
if data.get_id() == 1813:
You should write:
if data.get_id() == 1813:
it still occur the error
[recog] Traceback (most recent call last):
[recog] File «recog.py», line 43, in
[recog] if data.get_id() == 1803:
[recog] AttributeError: ‘list’ object has no attribute ‘get_id’
Can you please post your complete controller source code?
Can you please post your complete controller source code?
from so far it is like from controller import Robot from controller import Camera from controller import CameraRecognitionObject TIME_STEP = 64 robot = Robot() camera1=Camera('camera1') camera1.enable(TIME_STEP) camera1.recognitionEnable(TIME_STEP) wheels = [] data=[] wheelsNames = ['wheel1', 'wheel2', 'wheel3', 'wheel4'] for i in range(4): wheels.append(robot.getMotor(wheelsNames[i])) wheels[i].setPosition(float('inf')) wheels[i].setVelocity(0.0) while robot.step(timestep) != -1: leftSpeed = 0.0 rightSpeed = 0.0 cameraData = camera1.getImage() number = camera1.getRecognitionNumberOfObjects() data = camera1.getRecognitionObjects() for i in range(number): if data.get_id() == 1803: leftSpeed = 6.0 rightSpeed = 6.0 if((data.get_position())> -3): leftSpeed = 0.0 rightSpeed = 0.0
Can you try this:
[...]
data = camera1.getRecognitionObjects()
for d in data:
if d.get_id() == 1803:
[...]
Can you try this:
[...] data = camera1.getRecognitionObjects() for d in data: if d.get_id() == 1803: [...]
My aim is to scan all the objects in the image to check whether there exist the ideal id(which we have test and record before). Once confirmed, I want to get the z, x or y position of the object. ( for the next step). However, when I take use of python, I do not understand how to call database.
- Do I need to use the CameraRecognitionObject API?
Such as directly use
CameraRecognitionObject.get_id()
or use
data = camera1.getRecognitionObjects()
and use data.get_id() - how to call the position, do i need to built another 3 length array like
position =[3]
position=data[i].get_position()
and take use of position[2] to use the z-position?
and how could i know the objects’ id
is the class more like
data[i].get_position[k](in C language)?
how to write it in python?
Thanks a lot.
Yes, getRecognitionObjects() returns an array of CameraRecognitionObject which you can access using either the []operator or the for object in objects construct which I originally suggested.
Хорошо, это меня серьезно поставило в тупик, после нескольких часов попыток с блоком javascript ниже я все еще получаю ту же ошибку в отладчике javascript IE.
Я получаю сообщение об ошибке SCRIPT5007: невозможно получить значение свойства «get_id»: объект имеет значение null или не определен.
И ниже мой код:
AS.SP.ClientActions.ClientProgramEdit_Status = new AS.SP.ClientActions.ButtonStatus();
AS.SP.ClientActions.Can_ClientProgramEdit = function (groupID) {
var OnError = function (sender, args) {
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;
RefreshCommandUI();
};
var items = AS.SP.ClientActions.GetSelectedItems();
var count = CountDictionary(items);
if (count === 1) {
var itemID = items[0].id;
if (AS.SP.ClientActions.ClientProgramEdit_Status.itemID != itemID) {
AS.SP.ClientActions.ClientProgramEdit_Status.itemID = itemID;
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = false;
AS.SP.ClientActions.GetUrl(function (rootUrl) {
var fragments = AS.SP.Navigation.ParseUri(rootUrl);
var ctx = new SP.ClientContext(fragments.path);
var web = ctx.get_web();
var props = web.get_allProperties();
ctx.load(web);
ctx.load(props);
ctx.executeQueryAsync(function () {
var listId = 'Client Programs';
var sdlist = web.get_lists().getByTitle(listId);
var locationID = props.get_item('WL_ITEM_ID');
var query = new SP.CamlQuery();
query.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name="len_cp_Location" /><Value Type="Text">' + locationID + '</Value></Eq><Eq><FieldRef Name="len_cp_Client_Status" /><Value Type="Text">Inactive</Value></Eq></And></Where></Query><ViewFields><FieldRef Name="Title" /></ViewFields></View>');
var items = sdlist.getItems(query);
ctx.load(items);
ctx.executeQueryAsync(function () {
var item = items.itemAt(0);
var itemID = item.get_id();
if (itemID == "WL_ITEM_ID") {
AS.SP.ClientActions.ClientProgramEdit_Status.enabled = true;
RefreshCommandUI();
}
}, OnError);
}, OnError);
});
}
}
return AS.SP.ClientActions.ClientProgramEdit_Status.enabled;
}
Моя теория заключается в том, что я сделал что-то не так с моим CAML-запросом, но на данный момент я действительно не знаю, любая помощь в этом будет очень признательна, спасибо!
1 ответы
Вы используете items переменная дважды, один раз в строке 9:
var items = AS.SP.ClientActions.GetSelectedItems();
И снова внутри GetUrl:
var items = sdlist.getItems(query);
В замыкании executeQueryAsync возник конфликт имен. Я бы начал с решения этой проблемы. На какую коллекцию элементов вы хотите сослаться? Вы имеете в виду загрузить исходную переменную элементов:
ctx.load(items);
var items = sdlist.getItems(query);
Создан 03 июля ’12, 19:07
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
javascript
sharepoint-2010
caml
or задайте свой вопрос.
На моем веб-сайте wordpress я получаю ошибку ниже
Fatal error: Call to a member function get_id() on boolean in /home/customer/www/ae.testing.com/public_html/wp-content/themes/movedo-child/functions.php on line 33
Раньше работал нормально. но теперь, какой именно вопрос я не понимаю. если у кого-то есть идеи, дайте мне знать
Function.php следующим образом:
<?php
function movedo_child_theme_setup() {
}
add_action( 'after_setup_theme', 'movedo_child_theme_setup' );
function display_price_in_variation_option_name( $term ) {
echo $product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach($product_variations as $variation){
if(count($variation['attributes']) > 1){
return $term;
}
foreach($variation['attributes'] as $key => $slug){
if("attribute_" == mb_substr( $key, 0, 10 )){
$taxonomy = mb_substr( $key, 10 ) ;
$attribute = get_term_by('slug', $slug, $taxonomy);
if($attribute->name == $term){
$term .= " (" . wp_kses( wc_price($variation['display_price']), array()) . ")";
}
}
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
В строке « $ id = $ product-> get_id (); » я получаю эту ошибку.
2 ответа
Лучший ответ
Проблема кажется довольно простой, вы подключаетесь к after_setup_theme, которая запускается для каждого отдельного запроса wordpress. В этом контексте вы предполагаете, что у вас всегда есть продукт в контексте основного запроса, что не всегда верно.
Чтобы просто закрыть ошибку, оберните $ id = $ product-> get_id (); в такое, если так:
if(!empty($product)){
$id = $product->get_id();
}
...
Но чтобы сделать это действительно пуленепробиваемым, вы должны спросить себя, когда вы действительно хотите изучить wc_get_product, чтобы получить текущий продукт. Я предполагаю, что вы можете захотеть это только на странице сведений о продукте. Поскольку вы подключаетесь к ‘after_setup_theme’, можно использовать условные теги.
Измените свой код, чтобы вывести его из строя, как только он не выполняется на нужной странице, сделав что-то вроде этого:
function display_price_in_variation_option_name( $term ) {
if (!is_product()){
return;
}
echo $product = wc_get_product();
$id = $product->get_id();
...
1
Diego
7 Июн 2021 в 18:09
Wc_get_product каким-то образом возвращает false. Пытаться
global $product; //
0
Yoda — user264474
3 Фев 2022 в 13:25
вот php код
if(isset($_GET['id'])) {
//do something
} else {
redirect('index.php'); //redirect is a function
}
теперь, если id установлен (например: index.РНР?id=12), то действие выполняется, но если id не установлен (например, индекс.РНР?id=) это показывает ошибку, как ее преодолеть…??
Как определить id-это целое число, и оно не пустое, а затем выполнить определенное действие….
редактировать
спасибо всем за ваши ответы, но я все еще получаю эту ошибку…
if(isset($_GET['id'])) { // I implemented all these codes but still....
$user= User::find_by_id($_GET['id']);
// Database Classes Fetches user info from database
}
else {
redirect('index.php'); //redirect function
}
Если id равен 1 или больше 1, то скрипт выполняется отлично. ( индекс.РНР?id=1)
но id я установил id, отметив, что получаю ошибку i..индекс Е.РНР?id=
код должен автоматически перенаправлять пользователя на индекс.страница php вместо отображения ошибки…..
ошибка: запрос базы данных не удался: у вас есть ошибка в синтаксисе SQL; проверьте руководство, которое соответствует вашей версии сервера MySQL для правильного синтаксиса для использования рядом с «пределом 1» в строке 1
8 ответов
вы должны проверить и set-status и содержание:
if ( isset( $_GET['id'] ) && !empty( $_GET['id'] ) )
// ....
обратите внимание, что вы должны не используйте значение просто как есть и работайте с ним. Вы должны убедиться, что он содержит только ожидаемые значения. Чтобы проверить целое число и даже лучше работать с целым числом, сделайте что-то вроде этого:
$id = ( isset( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) ? intval( $_GET['id'] ) : 0;
if ( $id != 0 )
// id is an int != 0
else
redirect('index.php');
что говорит вам ошибка?
но это проверит, установлен ли он, и если это целое число
if(isset($_GET['id']) && ctype_digit($_GET['id']) && intval($_GET['id']) > 0)
is_numeric @ php.net
или проверить ctype_digit
if (!empty($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT))
или
if (!empty($_GET['id']) && ctype_digit($_GET['id']))
хорошо… Если вы настраиваете его как переменную целочисленного типа, вы также можете сделать следующее:
if($_GET['id'] && gettype($_GET['id']) == 'integer'){
#do something
}else{
#do something else
}
Как определить id — это целое число и он не пуст а затем выполните определенное действие….
if (!empty($_GET['id']) && (intval($_GET['id']) == $_GET['id'])) {
//do something
} else {
redirect('index.php'); //redirect is a function
}
вышеуказанное не может быть лучшим решением, но оно должно работать для того, что вам нужно. Он не позволит идентификатору быть 0 и потребует, чтобы он был целым числом.
if(isset($_GET['id']) && ctype_digit($_GET['id']) && is_numeric($_GET['id']) && $_GET['id']>0) {
$user= User::find_by_id($_GET['id']);
}
else {
redirect('index.php'); //redirect function
}
попробуйте это и этот код полный таблетки ваше требование.
похоже, у вас просто проблема с?id бросает true, когда вы хотите проверить, установлен ли его. Это потому, что он установлен, но не установлен на значение, которое вы хотели бы использовать.
Я предполагаю, что userids должны быть > 0, поэтому просто сделайте это
if (isset($_GET['id']) && $_GET['id'] > 0) {
$user= User::find_by_id($_GET['id']);
} else {
redirect('index.php');
}
Также вы, вероятно, лучше всего очищаете идентификатор перед обработкой его так
$userID = isset($_GET['id']) && $_GET['id'] > 0 ? (int) $_GET['id'] : 0;
if ($userID) {
$user= User::find_by_id($userID);
} else {
redirect('index.php');
}
есть много способов сделать это, лично я предпочитаю этот. Это делает ваш код немного чище.
вам придется проверять несколько раз для каждого возможного случая: что делать, если id не установлен или пуст? что делать, если id установлен, но это не цифра? что делать, если ключ » id » вообще не существует в запросе GET?
У меня была похожая ситуация. Я отправлял два вара с GET, одна цифра: «id», а другая-строка, которая была именем: «state»… Я решил проверить все возможные условия.
Сообщение было отмечено Хитрый Лис как решение

. Но лучше как я сказал, кода меньше
. Если только так как-то: