3

Here is the code of wordpress custom plugin.?

$pages = get_pages();
foreach ($pages as $page) {
  $pagee=$page->post_title;
}
echo $pagee; <---- I want here all pages name in variable.

please suggest how can i do it.

3
  • Declare the variable before the loop so it exists outside of the scope of the loop. Though it's not really clear if what you're asking is what you actually want, because the value will always equal the very last value from the loop. Commented Jun 14, 2018 at 12:40
  • 1
    make $pagee an array and add to it each foreach loop? $pagee[]=$page->post_title; Commented Jun 14, 2018 at 12:41
  • What do you wanna achieve? Commented Jun 14, 2018 at 12:43

4 Answers 4

4

You have just to append your variable like this

$pages = get_pages();
$pagee = array();
foreach ($pages as $page) {
  $pagee[] = $page->post_title;
}
echo implode(",",$pagee);
Sign up to request clarification or add additional context in comments.

2 Comments

or If i want result in array than? because i want to store this details in database. 'global $wpdb; $table_name = 'wp_seo_code'; $success = $wpdb->insert("wp_seo_code", array( "page" => $pagee, "code_true" => $code_true )); if ($success) { echo '<b style="color:green;"> Inserted successfully</b>'; } else { echo 'Not'; }'
Look at the edited code, now is working with array. If you want to store inside a db remember to access your array values by index.
1

You can store it as an array

foreach ($pages as $page) { 
    $pagee[]= $page->post_title; 
}  
print_r($pagee);

Eventually as long string

foreach ($pages as $page) { 
    $pagee.= $page->post_title . ' '; 
 }  
 echo $pagee;

Comments

1

You can do it this way:

// To save all pages
$allpages = array();
$pages = get_pages();
  foreach ($pages as $page) {
    // function array_push to insert the data at the end of the array
    array_push($allpages, $page->post_title);
  }
// Show the array
print_r($allpages);

or this:

$i = 0; // counter
$allpages = array(); // array to save all pages
$pages = get_pages();
  foreach ($pages as $page) {
    $allpages[$i] = $page->post_title; // save the value in the array by an index
    $i++; // increment the counter
  }

print_r($allpages);

Comments

0

Try declaring an array to store all values of $pagee while the loop runs:

$pages = get_pages();
$pagee = [];
foreach ($pages as $page) {
  $pagee[]=$page->post_title;
}
print_r($pagee); // print the array of all cycles

So, $pagee will contain all the values of $pagee for each cycle in the loop.

2 Comments

variables in a loop do not live in a different scope
@lovelace ah yes, I've made the appropriate edits, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.