Change AJAX Live Post Search Loop into foreach

I was told that the reason for why the live post search does not work is because the loop needs changing into a foreach.

This is the code:

add_action( 'wp_ajax_data_fetch' , 'data_fetch' ); add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); function data_fetch() {      global $  wpdb;     $  post_search_query = $  wpdb->get_results("SELECT * FROM wp_posts where post_type = 'post' and post_title like '%'".esc_attr( $  _POST['search_keyword'] )."'%'");          if( $  post_search_query->have_posts() ) :                  while( $  post_search_query->have_posts() ): $  post_search_query->the_post(); ?>                          <h5><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h5>             <span class="live-search-product-excerpt"><?php the_excerpt(); ?></span>              <?php endwhile;         wp_reset_postdata();     endif;     die(); } 

The search is dead. It shows nothing. Can someone please help me with this as I am at a loss. Here is the rest of the code:

add_shortcode('live_search', 'live_search_shortcode'); function live_search_shortcode(){      $  live_search = '<input type="text" class="live-search" name="postSearch" id="postSearch" placeholder="Type to Live Search"></input>     <div id="datafetch"></div>';          return $  live_search; }  add_action('wp_footer', 'jquery_live_search_data_fetch'); function jquery_live_search_data_fetch() { ?>      <script type="text/javascript">                  (function($  ){              var searchRequest = null;                                  jQuery(function (){                                      var minlength = 3;                                  jQuery("#postSearch").keyup(function (){                                          var that = this,                                      value = jQuery(this).val();                                  if (value.length >= minlength){                                      if (searchRequest != null)                      searchRequest.abort();                                  searchRequest = jQuery.ajax({                                      type: "POST",                     url: "<?php echo admin_url('admin-ajax.php'); ?>",                 data: {                 action: 'data_fetch',                 search_keyword : value                 },                                  dataType: "html",                 success: function(data){                                          if (value==jQuery(that).val()) {                                              jQuery('#datafetch').html(data);                     }                 }             }         );     } else {      jQuery('#datafetch').html( '' );     }   } ); }); } (jQuery));     </script> <?php } 

How to get a value-only flat array from $wpdb->get_results when selecting a single column, without foreach()?

My query is:

$  var = $  wpdb->get_results("SELECT field FROM {$  wpdb->prefix}table", ARRAY_A); var_dump($  var); 

it returns someting like array(2) { [0]=> array(1) { ["field"]=> string(5) "test1" } [1]=> array(1) { ["field"]=> string(t) "test2" }. I.e. each item is a row with a single name-value pair.

What I want is array(2) { [0]=> string(5) "test1" [1]=> string(5) "test2" }

Currently I achieve it like this:

$  var = $  wpdb->get_results("SELECT field FROM {$  wpdb->prefix}table"); foreach($  var as $  v_key => $  v_val) $  var[$  v_key] = $  v_val['field']; var_dump($  var); 

Is there a shorter way to do this?

How do I make my terms for each product display via foreach loop? (woocommerce)

This is my current loop to display my products via woocommerce. When I do print_r($ category_array); It returns the array, but when I try to use a function to call it so I can do what I want to with the data, it makes and my entire screen doesn’t display after the loop. Maybe it’s a mistake in my function? Still very new to woocommerce and wp_loops. Thank you

            <?php             // WP_Query arguments             $  args = array(                 'p'                      => 'product',                 'post_type'              => array( 'product' ),                 'order'                  => 'ASC',                 'post_per_page' => 20,             );              // The Query             $  query = new WP_Query( $  args );              // The Loop             if ( $  query->have_posts() ) {                 while ( $  query->have_posts() ) {                     $  query->the_post();                     function filter_categories($  categories) {                             foreach ($  categories as $  category) {                                 echo $  category->name;                             }                     }                       ?>                     <div class="row">                         <div class="col-2">                             <?php echo the_post_thumbnail(get_the_ID(), 'thumbnail'); ?>                         </div>                         <div class="col-7">                             <a href="<?= get_permalink(); ?>"><?= the_title()?></a>                             <br/>                             <?php                             $  category_array = get_the_terms(get_the_ID(), 'product_cat');                             filter_categories($  category_array);                             ?>                         </div>                         <div class="col-3 text-right ">Price</div>                     </div>                     <?php                 }             } else {                 // no posts found             }              // Restore original Post Data             wp_reset_postdata();             ?> 

issue with if/elseif in_array inside foreach loop display only one post

I try to attribute a specific background-color to each post if one of categories of post corresponding to one category. My function works but is restricted to display only one post in result. If I delete this function, all post are displayed.

More informations : On my page I have buttons to filter posts by category. if I click on once I display all post for this category. But each post contains several categories. I have selected some categories to attribute a background colors for each posts, but theses categories are different of the filters buttons.

WordPress display this error "a critical error has occurred on your site, Learn more about debugging WordPress." after the first post displayed.

here is my entire code :

<?php  add_action('wp_ajax_nopriv_filter', 'filter_ajax'); add_action('wp_ajax_filter','filter_ajax');  function filter_ajax(){  $  category = $  _POST['category'];  $  argsf = array(     'post_type' => 'post',     'posts_per_page' => -1,     'order' => 'ASC' );  if(isset($  category)){     $  argsf['category__in'] = array($  category); }  $  postsf = get_posts($  argsf);      if (!empty($  postsf)) {     foreach ($  postsf as $  post) {                  $  link_post = get_permalink( $  post->ID );         $  image_post = get_the_post_thumbnail_url( $  post->ID, $  size = 'large' );         $  item1 = get_post_meta($  post->ID, 'item1', true);         $  item2 = get_post_meta($  post->ID, 'item2', true);         $  item3 = get_post_meta($  post->ID, 'item3', true);         $  item4 = get_post_meta($  post->ID, 'item4', true);         $  title = get_the_title($  post->ID);          $  post_slug = $  post->post_name;         $  cats_post = wp_get_post_categories( $  post->ID );                  function test($  cats_post){             if (in_array("14", $  cats_post)){ echo'#710000';}             elseif(in_array("5", $  cats_post)){ echo'#0a005d';}             elseif(in_array("16", $  cats_post)){ echo'#65a0e8';}             elseif(in_array("13", $  cats_post)){ echo'#90744b';}         }      ?>   <div class="shop w-24 pb-1" style="height:320px; min-width:320px;">     <div class="w-100 h-100 p-2">                      <div class=" " style="background-color:<?php test($  cats_post); ?>">             <div class="">                 <!--<div class="" title="Locer">                 <a href="<?= $  item2; ?>"><i class="icofont-opposite "></i></a>                 </div>-->                 <div class="" title="something">                     <a href="tel:<?= $  item3; ?>"><i class="im im-phone"></i> </a>                 </div>                 <div class="">                     <span><?= $  item1; ?></span>                 </div>              </div>             <span class="text-uppercase col-white tsh332 fwlr text-center" style="font-size:2rem;">                 <?= $  title; ?>             </span>             <?php if ( metadata_exists( 'post', $  post->ID , 'item4' ) ){ ?>                  <div class="">                     <div class="b-yellow b-100">                         <span><?= $  item4; ?> </span>                     </div>                 </div>             <?php } ?>         </div>                      </div> </div> <?php  }  /* fin foreach */     }  /* fin if  */ wp_reset_postdata(); die(); } 


I tried that but it doesn’t work :

  • get_the_category instead of wp_get_post_categories
  • has_item instead of in_array

I don’t know If I must use an other foreach loop and how !


How to make variable update for each instance of for-each loop?

I have a for-each loop that goes through a file directory. These files are transaction information from different clients. When there is an error with a file (i.e. can’t be processed), the Event Handler is to send an email to the client notifying them. There is a SQL task that uses an existing variable (Client ID from the file) that queries a table to get the Client’s email address. I created a variable for the Client Email. I want to make this update each time the for-each loop is run, since each file will have a different value for the client email variable.

How can I ensure this?

Inside the for-each loop, there are three data flow tasks that could conceivably "error" and that’s when I will be sending these notification emails. Will I need to scope a variable for each of the three executables within the loop for the Client Email? Or can I scope a single variable in the for-each loop?

I understand this may be a bit confusing so please let me know if you have any questions.

Event Handler Flow

For-Each loop with data flow task

PHP Warning: Invalid argument supplied for foreach() in /home/padtvro/public_html/wp-content/themes/claudia/content.php on line 30

I have a problem, it is generated in woprdpree in cpanel error log this error: PHP Warning: Invalid argument supplied for foreach () in /home/padtvro/public_html/wp-content/themes/claudia/content.php on line 30 If I delete it, it appears again in 6-7 hours. What’s the problem?

<section id="contents" class="clearfix"><div class="row main_content"><div class="container content_wraper"><?php the_breadcrumb(); ?><div class="grid_8" id="content"><div class="widget_container content_page"><?php require_once dirname(__FILE__) . '/include/cat.php'; ?>  </div></div><div class="grid_4 p7ehc-a" id="sidebar"> <?php $  ge_sidebar = '';                  if (is_search()) {                       $  ge_sidebar = of_get_option('se_sidebar','');                     }else if(is_category() ) {                          $  category = get_the_category();                                               $  cn_sidebar ='';                         foreach($  category as $  ca_id) {                             if(empty($  cn_sidebar)) { $  cn_sidebar = of_get_option('cat_'.$  ca_id->term_id);}                                                        }                          if(empty($  cn_sidebar)) {                             $  ge_sidebar = of_get_option('cat_sidebar','');                         } else { $  ge_sidebar = $  cn_sidebar; }                       } else if(is_author() ) {                          $  ge_sidebar = of_get_option('au_sidebar','');                      }else if(is_tag() ) {                          $  tags = get_the_tags();                                               $  cn_sidebar ='';                         foreach($  tags as $  tg_id) {                             if(empty($  cn_sidebar)) { $  cn_sidebar = of_get_option('tag_'.$  tg_id->term_id);}                                                       }                          if(empty($  cn_sidebar)) {                             $  ge_sidebar = of_get_option('tag_sidebar','');                         } else { $  ge_sidebar = $  cn_sidebar; }                     }                                   $  dyn_sidebar ='';                 if(!empty($  ge_sidebar)) {   $  dyn_sidebar = $  ge_sidebar; };                                foreach ( $  GLOBALS['wp_registered_sidebars'] as $  sidebar ) {                     if($  sidebar['name'] == $  dyn_sidebar)                         {                              $  dyn_sidebar = $  sidebar['id'];                         }                 }                   if(!empty($  dyn_sidebar)) {                     if (is_active_sidebar($  dyn_sidebar)) : dynamic_sidebar($  dyn_sidebar);                     endif;                   } else{                     if (is_active_sidebar('center-sidebar')) : dynamic_sidebar('center-sidebar');                     endif;                 }      ?></div><div class="clear"></div></div></div></section>  

How to change order inside foreach using wp_enqueue_script?

I have a created a for each loop to load all the script files from my build folder dynamically in the footer with for development and production mode. This way I don’t need to manually replace the script files.

But I have a problem, I don’t know how to change the order of the files to a specific order.

It should be: Runtime, Vendors, Main.

This is my PHP code:

// First check if "JS" folder exist to prevent errors. if(is_dir(THEME_DIR_ASSETS . '/js')) {     // Enqueue all scripts.     function nm_enqueue_scripts() {     $  directoryJS = new DirectoryIterator(THEME_DIR_ASSETS . '/js');          wp_deregister_script('jquery');         wp_enqueue_script('jquery', '', array(), null, false);          foreach ($  directoryJS as $  file) {             if (pathinfo($  file, PATHINFO_EXTENSION) === 'js') {             $  fullName = basename($  file);             $  name = substr(basename($  fullName), 0, strpos(basename($  fullName), '.'));              wp_enqueue_script($  name, THEME_DIR_JS . '/' . $  fullName, $  name, null, true);             }         }     }     add_action('wp_enqueue_scripts', 'nm_enqueue_scripts'); } 

How can I do this?

Foreach: data-type = ‘group’

I have a problem with foreach with data-type = ‘group’. Maybe someone could suggest something. I don’t know how to refer to an array in a loop and how to define specific types of values e.g. images, WYSIWYG instead of value itself. I have this:

<?php      $  fields = get_field_objects();      ?>      <?php if ($  fields): ?>         <div class="slider slider-for">             <?php foreach ($  fields as $  field): ?>                  <?php if ($  field['value']): ?>                     <div class="slider-nav-box-big" id="<?php echo $  field['name']; ?>">                         <div class="col-md-4 col-sm-12 col-12 slider-for-img">                             <img src="<?php echo $  field['value']; ?>" alt="">                         </div>                         <div class="col-md-8 col-sm-12 col-12 slider-for-description">                             <p>                                 <span><?php echo $  field['label']; ?></span>                                 <?php echo $  field['wysiwyg']; ?>                             </p>                         </div>                     </div>                 <?php endif; ?>              <?php endforeach; ?>         </div>     <?php endif; ?> 

$ field[‘value’] obviously returns an empty Array, and $ field[‘wysiwyg’] doesn’t work at all, but I don’t know how to improve it.

A code that I could not fully grasp related to foreach & count_user_posts()

Working on my first WordPress theme, I created a page template for authors based on this tutorial which is itself based on the twenty-fourteen theme.

What I could not understand is this :

$  post_count = count_user_posts( $  contributor_id ); 

From this code example (check especially the first 10 lines for my first question which will very possibly automatically answer my final questions):

<?php // Output the authors list. $  contributor_ids = get_users( array(   'fields'  => 'ID',   'orderby' => 'post_count',   'order'   => 'DESC',   'who'     => 'authors', ));  foreach ( $  contributor_ids as $  contributor_id ) : $  post_count = count_user_posts( $  contributor_id );   // Move on if user has not published a post (yet).   if ( ! $  post_count ) {     continue;   } ?>  <div class="contributor">   <div class="contributor-info">     <div class="contributor-avatar"><?php echo get_avatar( $  contributor_id, 132 ); ?></div>     <div class="contributor-summary">       <h2 class="contributor-name"><?php echo get_the_author_meta( 'display_name', $  contributor_id ); ?></h2>       <p class="contributor-bio">         <?php echo get_the_author_meta( 'description', $  contributor_id ); ?>       </p>       <a class="button contributor-posts-link" href="<?php echo esc_url( get_author_posts_url( $  contributor_id ) ); ?>">         <?php printf( _n( '%d Article', '%d Articles', $  post_count, 'twentyfourteen' ), $  post_count ); ?>       </a>     </div><!-- .contributor-summary -->   </div><!-- .contributor-info --> </div><!-- .contributor -->  <?php endforeach; ?> 

I have checked the Codex for count_user_posts( ) but I could not understand how the code is aligned with the documentation as the output of the foreach loop $ contributor_id is not only the ID but also post_count,desc and authors.

These are supposed to be the second parameters which are optional and are

Single post type or array of post types

as the Codex specifies below:

$ post_type (array|string) (Optional) Single post type or array of post types to count the number of posts for. Default value: ‘post’

So how the values of “post_count” ,”desc” and “authors”. fit with the Codex documentation?

Same question for:

get_avatar( $  contributor_id, 132 ) 


get_the_author_meta( 'display_name', $  contributor_id ) 

Invalid Argument foreach

Is this because of WordPress, PHP, or the Theme? (or some combination)

A client of mine has a WordPress site that’s been working just fine for years, but recently started getting the following errors pulling up in it’s sidebars:

Warning: Invalid argument supplied for foreach() in /wp-content/themes/epsilon/page-threecolumn.php on line 29

Been thinking it may have to do with upgrades to both WordPress and PHP. Theme is no longer supported. Here is what the code looks like in that area:

                <div class="col-234">                     <div class="sidebar left-sidebar">                             <?php                             $  leftsidebar = simple_fields_get_post_group_values($  post->ID, "Left Sidebar", false, 2);                             foreach ($  leftsidebar as $  value) {                              ?>                             <aside>                                 <h2> <?php echo $  value[1]; ?></h2>                                 <div>                                 <?php                                     if($  value[2]):                                         if (function_exists('cforms_insert')){                                              echo cforms_insert(do_shortcode($  value[2]));                                          } else {                                              echo do_shortcode($  value[2]);                                          }                                      endif;                                 ?>                                 </div>                             </aside>                             <?php } ?>                     </div>                 </div> 

I did not build the site. And while I am proficient in pure HTML, I know little about PHP. Is this just a syntax issue that can be resolved with some quick fixes? Or do I need to go out and install a completely new theme (which scares the heck out of me)?