WordPress.org

Forums

Search working also for dynamically generated content (e.g. from shortcodes) (3 posts)

  1. crysman
    Member
    Posted 1 year ago #

    Please, what could help me to achieve that WP search ?s=xxx
    works also for dynamically generated content?

    We have some shortcodes generating content from our database. Unfortunatelly, WP default search engine searches only the posts/pages content (content inserted via WP post tinyMCE editor) :(

    I have some ideas how to implement it, but it is a lot of work and maybe somebody has already solved this somehow, so no need for me to "discover America again"...

    Thanks a lot for any hints, links or ideas!

  2. SEO Peter
    Member
    Posted 1 year ago #

    Insert into THEME_DIR/functions.php

    add_filter( 'pre_get_posts', array('myClass','wphook__pre_get_posts'), 1 );
    
    class myClass{
    
    	protected $isMainLoop = TRUE;
    
    	public function wphook__pre_get_posts( $query ){
    		if( ! $this->isMainLoop ){
    			return $query;
    		}
    		$this->isMainLoop = FALSE;
    
    		if( $query->is_search ){
    			$query->set('post_type',array('post','books','portfolio','another_custom_post_type'));
    
    		}
    		return $query;
    	}
    }
  3. crysman
    Member
    Posted 1 year ago #

    I had to modify it like this to stop PHP complaining about "using this in wrong context":

    class myCustomSearch{
      	protected $isMainLoop = TRUE;
    
      	public function wphook__pre_get_posts( $query ){
      		if( ! $this->isMainLoop ){
      			return $query;
      		}
      		$this->isMainLoop = FALSE;
    
      		if( $query->is_search ){
      			$query->set('post_type', array('post','page'));
      		}
      		return $query;
      	}
      }
      $myCustomSearch = new myCustomSearch();
      add_filter( 'pre_get_posts', array($myCustomSearch,'wphook__pre_get_posts'), 1 );

    (I had to create an object and pass it to the add_filter)

    But it does not work. It finds nothing in the dynamically generated content. Any further ideas? :(

Topic Closed

This topic has been closed to new replies.

About this Topic