• I’m trying to find if a page exists and I’m using this clumsy code:

    function searchPageContent($contents){
      $pages=new WP_Query( array('post_type'=>'page') );
      if($pages->have_posts()){
        while($pages->have_posts()){
          $pages->the_post();
          $PID=$pages->post->ID;
          $post=$pages->posts[0]->post_content;
          if(substr($post, 0, strlen($contents)) === $contents){
            return $PID;
          }
        }
      }
      return 0;
    }

    If the page exists which starts with the required content, it returns the Page ID.

    This seems to work but is awfully clumsy.

    Is there a better way?

Viewing 1 replies (of 1 total)
  • dgcov

    Maybe you can try this

    /**
     * @global WPDB $wpdb
     * @return int|null Returns the Page's ID if found, or null if page is not found with the content
     */
    function searchPageContent($content){
        global $wpdb;
        $query = 'SELECT * FROM <code>'.$wpdb->posts.'</code> WHERE post_type="page" AND post_content LIKE "%s" ';
        $query = $wpdb->prepare($query, $content.'%');
        $post_id = $wpdb->get_var($query);
        return $post_id;
    }

    It does the search in the MySQL itself and returns only the Page’s ID

Viewing 1 replies (of 1 total)
  • The topic ‘Search for page by content’ is closed to new replies.