1

Similarly to this topic I need to extract some page IDs from user input (a theme options admin page), store them in a variable, and then filter using the is_page() filter. The input consists of numerical IDs separated by newlines, although if I get this working I'll refactor to allow page slugs too.

Based on the answer to the linked topic, I have the following, But it still does not work. The variable spits out a proper array of IDs, but is_page() doesn't filter based on the array.

// Wordpress my_conditional_load stuff code above

function my_option_pages() {
  $pages = get_option(esc_textarea('my_conditional_load', ''));
  return $pages; // reusable variable; used in form and also below
}

function my_option_result() {
  $pages = my_option_pages();
  $page = array_map(trim, explode(PHP_EOL, $pages)); // create array; split string at newline
  $result = implode( ', ', $page ); // reassemble as comma delimited list
  $result = rtrim($result); // get rid of extra whitespace
  return $result; // string; resusable variable used below end elsewhere. Must be a string for other uses.
}

add_filter( 'the_content', 'test_the_variable' );

function test_the_variable( $content ) {

  $result = my_option_result();
  $result = explode(', ', $result); // recreate the array

  if ( is_page( array( $result ) ) ) {
    echo '<span class="foo hide">Array $result = ';
    print_r($result);
    echo '</span>';
  }
  else {
    echo '<span class="bar hide">Array $result is EMPTY! But we found this: ';
    print_r($result);
    echo '</span>';
  }
  return $content;
}

This page is a working example. It's page ID 9, which is in the array. Open DevTools and find the string bar hide in the page source. You can see the array:

<span class="bar hide">Array $result is EMPTY! But we found this: Array
  (
    [0] => 9
    [1] => 6604
    [2] => 6509
    [3] => 7323
  )
</span>

So what's wrong?

1
  • Are the other IDs also pages? Also, are you on the Page (and it is a Page post type, correct?) with ID 9 when testing this?
    – phatskat
    Mar 1, 2019 at 22:14

1 Answer 1

1

In is_page you are passing an array with one element that is also an array. Since $result is already an array, you should do

if ( is_page( $result ) ){ 
1
  • I just figured that out on my own! But glad I asked anyway so this answer will be available to the next mook trying to solve this! Mar 1, 2019 at 23:50

Your Answer

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

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