0

Im trying to loop through my custom data in a table to display on the page. Everything is working as intended except the posting to a page using the wp_update_post() function.

Here is my function:

function update_insert_page() {
  global $wpdb;
    $table_name = $wpdb->base_prefix . 'portalorgs';
    $info = $wpdb->get_results( "SELECT * FROM $table_name" );

  foreach ($info as $inf) {
    $orgname = $inf->name;


    $insertpage = array(
        'ID'           => 224,
        'post_content' => $orgname . '<br />'
    );

    wp_update_post( $insertpage );

  }


}

It displays and loops correctly on var_dump

Name: Home
Name: stugotz
Name: tupac
Name: mister2
Name: Okman
Name: MrOk

But on the actual page itself it only posts the last one:

MrOk

I want to be able to display ALL the names from the DB instead of the last one. For reference the update_insert_page() function gets called in a plugin.

5
  • why you are using 224 ID for all post in loop? Oct 2 '19 at 11:45
  • @Chetan Vaghela Just a test page but in the actual application the page won't change since i'm embedding that page into another page. My goal is to build upon the post when new data gets created.
    – RickRome
    Oct 2 '19 at 11:53
  • you want to add all orgname into test page content. right ? Oct 2 '19 at 11:56
  • @Chetan Vaghela yeah thats the goal, when that function gets called to be able to update the page content with data in that table
    – RickRome
    Oct 2 '19 at 12:01
  • i have added answer. please check and let me know if this helps to you. Oct 2 '19 at 12:05
0

Try below code. it will get all data from that table and update page content. you can modify as per your need. let me know if this works for you.i assume that $inf->name is return just names.

function update_insert_page() {
    global $wpdb;
    $table_name = $wpdb->base_prefix . 'portalorgs';
    $info = $wpdb->get_results( "SELECT * FROM $table_name" );

  $orgname = '';
  if(!empty($info))
  {
    foreach ($info as $inf) {
      $orgname .= 'Name :'.$inf->name.'<br/>';
    }
     $insertpage = array(
      'ID'           => 224,
      'post_content' => $orgname
    );
    wp_update_post( $insertpage );
   }

}
2
  • Yep this works. I had to set the variable I want outside the foreach loop and then use that multistring concatenation?
    – RickRome
    Oct 2 '19 at 12:29
  • yeah. that is correct. Oct 2 '19 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.