I have this PHP code that produces a warning:
Warning: Invalid argument supplied for foreach() php wordpress
Here is the code:
<?php
$post_status1 = 'publish';
$post_type1 = 'page';
$featucat = "about";
$featucount = "1";
$my_query = new WP_Query('post_status='. $post_status1 .'&post_type='. $post_type1.'');
if ($my_query->have_posts()){
while ($my_query->have_posts()) : $my_query->the_post();
$front_values = get_post_custom_values('Homepage_Blog_01p', get_the_ID());
foreach ( $front_values as $front_key => $result_value ) {
if($result_value == 'about') {
?>
<div class="thewidgets">
<?php
$description_values = get_post_custom_values('Description_Field', get_the_ID());
foreach ( $description_values as $description_key => $description_value ) {
echo $description_value;
}
?>
<a href="<?php the_permalink(); ?>" title="Read the whole post" class="rm">Read More</a>
</div>
<?php } } endwhile; } ?>
Here is the full error:
Warning: Invalid argument supplied for foreach() in
D:PROGRAM FILESwampwwwwestchesterwp-contentthemes
computerrepairfooter.php on line 22"
What am I doing wrong?
asked Aug 18, 2013 at 20:00
$front_values
is not an array if you’re getting that. Check its contents, and if it’s legitimately not an array at times (for example, if get_post_custom_values
returns null
when there aren’t any results), account for it by wrapping the foreach
in an if(is_array($front_values)) {
conditional.
answered Aug 18, 2013 at 20:02
ceejayozceejayoz
174k40 gold badges295 silver badges363 bronze badges
4
How to reproduce this PHP warning:
Put this in a.php
:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //warning happens on this line.
print "ok";
}
?>
Prints:
eric@dev ~ $ php a.php
PHP Warning: Invalid argument supplied for foreach() in
/var/www/sandbox/eric/code/php/run06/a.php on line 3
PHP Stack trace:
The warning means exactly what it says. You passed a parameter into the foreach structure which could not be evaluated in the foreach. Before the foreach loop, ensure that the first parameter is a structure that the foreach can handle.
answered Aug 11, 2014 at 18:03
Eric LeschinskiEric Leschinski
142k95 gold badges407 silver badges332 bronze badges
<?php wp_head(); ?>
Add this code in the head tag. I think it will solve your warning — Warning: Invalid argument supplied for foreach() in C:wamp64wwwdevelopmentwp-includesscript-loader.php on line 2652
answered Jul 26, 2021 at 16:15
Разрабатывая свой код на PHP, программист может столкнуться с сообщением об ошибке «Invalid argument supplied for foreach in…». После данного сообщения обычно следует указание на её конкретику, к примеру, «/modules/tasks/todo_tasks_sub.php on line 121». Ошибка обычно обусловлена спецификой имеющегося отрезка кода, и требует проверки особенностей использования в нём переменных. Давайте разберём факторы появления ошибки, и как её можно исправить.
Содержание
- Причины появления Invalid argument supplied for foreach
- Как исправить ошибку «Invalid argument supplied for foreach in»
- Ошибка в WordPress
- Заключение
Причины появления Invalid argument supplied for foreach
Рассматриваемая ошибка обычно возникает в ситуации, когда переменная, которую foreach пытается выполнить (повторить) не является массивом. К примеру, вы передаёте в цикл не массив, а скаляр, или вы задействуйте двойной массив, и забыли определить, как выбирается индекс.
Давайте допустим, что мы имеем функцию с именем get_user_posts. Эта функция должна возвращать массив комментариев пользователя. Однако если комментариев нет, функция возвращает логическое значение FALSE.
В приведенном выше отрезке кода мы предположили, что переменная $ posts всегда будет массивом. Однако, если функция get_user_posts возвращает логическое значение FALSE, то цикл foreach не будет работать, и PHP выведет следующее сообщение об ошибке:
Warning: Invalid argument supplied for foreach() on line 7
Как же решить указанную проблему? Давайте разбираться.
Как исправить ошибку «Invalid argument supplied for foreach in»
Решение зависит от того, для чего предназначен ваш код. То есть, если функция get_user_posts всегда должна возвращать массив, то, очевидно, вам необходимо выяснить, почему она возвращает логическое значение FALSE или значение NULL. Причиной этому может быть несколько вещей:
- Не удалось объявить пустой массив «по умолчанию» (default);
- Сбой запроса к базе данных;
- Массив перезаписывается или сбрасывается. Это часто происходит в скриптах с большим количеством массивов, когда имеются ограничения памяти, а разработчик вынужден сбрасывать массивы, с которыми он или она закончили работу.
Просматривая чей-либо код, мы можем столкнуться с API и функциями, которые возвращают значение FALSE, когда результаты отсутствуют. Если это так, то вы можете добавить следующую проверку в ваш код:
Выше мы используем функцию is_array, чтобы проверить, является ли $posts массивом. И это мы делаем ДО того, как пытаемся зациклить его с помощью конструкции foreach. Как мы уже писали, все зависит от того, каково предназначение вашего скрипта. Добавление проверки is_array неразумно в ситуации, когда есть вопросы о том будет ли переменная массивом. Ведь вы будете скрывать ошибку, которой не должно существовать.
Ошибка в WordPress
Также рассматриваемая ошибка может появляться при работе сайтов на WordPress. Проблема вызвана тем, что WP_Block_Parser выполняет несколько строковых манипуляций с substr () и strlen (), предполагая, что они работают с одиночными байтами, а не с многобайтовыми последовательностями.
Решить ошибку Invalid argument supplied for foreach в WordPress помогает изменение значения настройки mbstring.func_overload на 0 (обычно стоит 2). Сохраните произведённые изменения, и попытайтесь перейти на проблемную ранее страницу.
Если это не помогло, попробуйте скачать Вордпресс 4.9.5, вытянуть из него папку wp-includes, и скопировать в аналогичную папку на вашем хостинге. После этого WordPress может предложить обновить ваши базы данных, соглашайтесь, и всё заработает после очистки кэша.
Заключение
Ошибка «Invalid argument supplied for foreach in…» в коде PHP обычно вызвана переменной, не являющейся массивом. Последнюю пытается выполнить foreach, но безуспешно. Для решения возникшей проблемы можно добавить функцию is_array (она проверит, является ли переменная массивом). Также может порекомендовать общий ознакомительный материал на сайте phpfaq.ru, где детально разобрано, как найти ошибку в созданном вами коде.
I recently moved a wordpress install from my local instance to a dev server. For the move, I installed a clean version of wordpress 3.4, moved exact duplicates of the file structre, and used the import / export feature to bring the posts in.
I then went in and set the necessary widgets, and settings. I’ve done this 100 times, and never had this problem. Here is the error:
Warning: Invalid argument supplied for foreach()
in /home/content/46/9411746/html/dev/wp-admin/includes/plugin.php on line 1285
It only appears in the admin menu. I see it when I try to add a widget, change a setting, work with menus, or update meta data for a post. It pops up all over the admin menu.
Here is the function triggering the error in includes/plugin.php
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) {
if ( $menu_slug == $item[2] ) {
unset( $menu[$i] );
return $item;
}
}
return false;
}
I’m using appearance > menus and have two registered here in functions.php here:
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
register_nav_menus(
array(
'header-nav' => __( 'Main Header Navigation', 'kyosay' ),
'footer-nav' => __( 'Footer Navigation', 'kyosay' )
)
);
}
I am doing some other customization of the admin panel, reordering some menu items and eliminating others that my clients don’t need. I can include that code if you think it’s relevant.
Since this issue is triggered in core, I’m at a loss as to how to fix it. NOTE: The issue is not happening on my local build. Thoughts?
Edit: added remove_menu_items code from functions.php for reference
function remove_menu_items() {
remove_menu_page('link-manager.php'); // Links
remove_menu_page('edit-comments.php'); // Comments
}
add_action( 'admin_init', 'remove_menu_items' );
Update:
I have eliminated functions.php as the source of this issue. It seems to be triggered on Ajax events (dragging a new widget to a sidebar, updating a meta-box, etc. I’m going to uninstall and reinstall and see if it’s still happening. Could this have something to do with the web host (godaddy) ? It’s not showing up on my local build at all.
Skip to content
Support » Fixing WordPress » Invalid argument supplied for foreach() in class-wp-post-type.php
-
After updating to the latest WP version, the following is appearing in the error log…
PHP Warning: Invalid argument supplied for foreach() in …/wp-includes/class-wp-post-type.php on line 526
It cycles by repeating every few seconds then calms down for about 3 minutes, then repeating every few seconds then calms down for about another 3 minutes.
As this is a core php file in WP, are we looking at waiting for an update for this to be corrected? Or is there something we can do in the interim until this is corrected (fully realizing this will be overwritten – or should be – by the next update)? I’m not a programmer, more of a tinkerer.
Thanks in advance.
The page I need help with: [log in to see the link]
- The topic ‘Invalid argument supplied for foreach() in class-wp-post-type.php’ is closed to new replies.
At some point in the life of a PHP developer, he will come across the error “Warning: Invalid argument supplied for foreach()». This error is encountered when you are trying to pass an invalid argument for the foreach() function, that it cannot understand.
In this article, we will try to understand the root cause of this error and the ways to prevent it.
What is «Warning: Invalid Argument Supplied for foreach()» Error?
This error usually occurs when you are trying to pass a string value to the PHP built-in function foreach(). As the foreach() method is used for iterating over an array of elements, it expects an array from the user. When it receives anything other than an array, such as a string if throws the error.
Example 1
<?php
$mystring = 'Stechies';
foreach($mystring as $ms){
echo 'Array Value: '.$ms;
}
?>
Output
Warning: Invalid argument supplied for foreach() in foreach.php on line 4
Correct Code
<?php
$mystring = array('S','T','E','C','H','I','E','S');
foreach($mystring as $ms){
echo ' '.$ms;
}
?>
Output
S T E C H I E S
Explanation
In the program given above, you can see that the foreach() method is passed the argument $mystring, which is an array. $mystring is converted into an array using the in-built array() method. So, the loop iterates over the array and prints out the elements with space in between them, as mentioned in the code.
Example 2: Program to Check If an Object Is an Array or Not
<?php
$mystring = array('S','T','E','C','H','I','E','S');
if(is_array($mystring) || is_object($mystring)){
foreach($mystring as $ms){
echo ' '.$ms;
}
}
?>
Output
S T E C H I E S
Explanation
Here, you can see that the array stored in the variable $mystring is evaluated to see whether it is an array or an object. Inside the if statement two methods are used, is_array() and is_object(). The is_array() method is used for checking if a variable is an array or not. The is_object() function is used for checking if a variable is an object or not.
The if statement checks whether $mystring is an object or an array. As there is an OR in between the statements, if either one of the conditions are True, the foreach() method iterates over the array elements and displays them using the echo statement. The result shows that the characters have a space in between.
Example 3: Force Conversion of a String to Array
<?php
$mystring = 'STECHIES';
$mystring = is_array($mystring) ? $mystring : array();
foreach($mystring as $ms){
echo ' '.$ms;
}
?>
Output
STECHIES
Explanation
The code here demonstrates how a string can be converted into an array. You can observe that the is_array() method accepts the $mystring variable as the argument. The conditional statement in the second line checks if the variable is an array or not. If it is false, the $mystring is converted into an array using the array() method.
Then the foreach() method is used for iterating over the elements of the array and printing them out using the echo statement.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Comments
ocean90
changed the title
Warning: Invalid argument supplied for foreach() in /var/www/orthodox/data/www/orthodoxchurch.ru/wp-includes/blocks.php on line 183
Warning: Invalid argument supplied for foreach() in /wp-includes/blocks.php on line 183
Dec 7, 2018
Hi @dimitrisindaryov,
Thanks for the report.
Based on the PHP error notice, it looks like WP_Block_Type_Registry::get_instance()->get_all_registered()
may be failing to return an array.
https://github.com/WordPress/WordPress/blob/5.0-branch/wp-includes/blocks.php#L106-L107
I’m curious why this would be the case though, because WP_Block_Type_Registry
‘s internal class variables can’t be modified by plugins.
Can you share which plugins you’re running? Also, have you tried deactivating each plugin one by one to see if the PHP error notice might be related to one of them?
Accelerated Mobile Pages
Akismet Anti-Spam
All In One SEO Pack
All In One WP Security
AntiVirus
Bg Bible References
Classic Editor
Contact Form 7
Cyclone Slider
Easy WP Meta Description
Elementor
Google Analytics Dashboard for WP (GADWP)Автор: ExactMetrics | Детали
Google Analytics for WordPress by MonsterInsights
HayyaBuild
ImageRecycle pdf & image compression
iThemes Security
MailChimp для WordPress
Meta Description
Meta Tags Generator
Newsletter — Archive
Orbit Fox Companion
Pageviews
Popups, Lead Forms, Surveys, Live Chats WordPress Plugin — GetSiteControl
Post Views Counter
Redirection
Responsible
Security by CleanTalkGet
SEO Bulk Editor
Slide Anything — Responsive Content / HTML Slider and CarouselSimon Edge | Детали
Smart Slider 3
Subscribe2
Webcraftic Clearfy
Webcraftic Robin image optimizer
Webcraftic Скрыть страницу логина
WordPress Related Posts
WP Fastest Cache
WP Featherlight
WP Meta SEO
WP Speed of Light
WP Super Cache
WP Translitera
WP-PageNavi
WP-PostRatings
WP-PostViews
Yandex.Metrika
Yet Another Stars Rating
YouTube
YouTube Embed
Мобильное меню
Шорткоды
Яндекс.Дзен.
Яндекс.Поделиться
Яндекс.Турбо
This happened when your new editor turned on for the fifth version of WordPress.
@dimitrisindaryov Have you tried deactivating each plugin one by one to see if the PHP error notice might be related to one of them?
I turned off all the plugins. Nothing helps.
Hellow!
I have same problem 2 web sites. (This happened when your new editor turned on for the fifth version of WordPress.)
I dont have plugins (on test site template is stock)
Please help!
Hi.
I have just installed WP 5.0.3 to my local environment. It’s a clean setup with default settings (twentynineteen theme, no plugins working, no posts). And I have the same error.
Hello )
in all posts in a classic editor switch to plain editor
and remove «<!-- wp:paragraph -->
» and all tegs with <!-- /wp:tegs -->
RUS:
Всем привет!
Я удалил в ручном режиме во всех постах <!-- wp:тэг-->
В классическом редакторе переключив на текст.
Ошибка пропала.
Всем удачи!
I’m having the same issue. I found that it happens only on PHP 7.2. Do you using this version? Try to rollback to PHP 7.1 or older. and your problem will be gone.
Сделал проверку и ошибка ушла:
if ( is_array( $block['innerContent'] ) ) {
foreach ( $block['innerContent'] as $chunk ) {
$block_content .= is_string( $chunk ) ? $chunk : render_block( $block['innerBlocks'][ $index++ ] );
}
}
This Code has moved to Core and is not maintained in the plugin anymore. Anyone willing to create a trac ticket instead?
While working on a WordPress project, I got a PHP warning.
Warning: Invalid argument supplied for foreach() in …
We can easily hide warnings in PHP. But I like to learn more about such simple matters in deep.
Actually this error is coming from a foreach loop. I just try to var_dump
values in an array using this foreach loop.
foreach ($items as $item) {
// ...
}
In the PHP manual, it says that
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
This is the basic cause behind this warning. We are passing something to foreach loop that is not an array.
To solve this warning, we have two simple options at here.
Solution 1
We can check the type of that variable & if it is an array, then only pass it to the foreach loop.
if (is_array($items)) {
foreach ($items as $item) {
// ...
}
}
Now we ensure that we have an array for foreach loop.
Solution 2
We can also solve this warning by cast that variable to an array in the loop. This is a lot cleaner, requires less typing and only needs one edit on a single line.
foreach ((array) $items as $item) {
// ...
}
If we cast any value to an array, we will get an array whatever value it was.
Recent Posts
- Solve «ValueError invalid literal for int() with base 10» — Python
- Handling dynamic subdomain with Flask — Python
- A minimal example about WordPress object cache
- Select random element from a list — Python
- Write our first Selenium program with Python 3 & Firefox
This article was published on September 10, 2014
Your Questions / Comments
If you found this article interesting, found errors, or just want to discuss about it, please get in touch.