简体   繁体   中英

Adding Custom Post Types/ Fields to Wordpress Search

I am looking for an easy way to add support for Custom Post Types with Custom Fields in them, to the search function in my Wordpress site. I am fine with doing it either programmatically or with a plugin, but the plugins I have tried made no sense.

Currently when I search, only the titles of my custom post types will appear in the search, but I want to be able to search by something like what I have in my post type, accounts, for instance, the person associated with that account. Basically I want to be able to type Johnny Appleseed, and even though the title of his account is not his name, his name is a custom field called contact_name.

How can this be done?

add this "'query_var' => true,"

add above code when you are creating custom post type.

for more info follow this : https://codex.wordpress.org/Function_Reference/register_post_type

if you are using any plugin the user below code


add_filter( 'pre_get_posts', 'tgm_cpt_search' );
/**
* This function modifies the main WordPress query to include an array of post types instead of the default 'post' post type.
*
* @param mixed $query The original query
* @return $query The amended query
*/
function tgm_cpt_search( $query ) {
if ( $query->is_search )
$query->set( 'post_type', array( 'post', 'movies', 'products', 'portfolio' ) );
return $query;
};

You don't need plugins, you need to modify (or create) search.php in the root of your theme. Model it after archive.php, and inside the main loop

<?php while (have_posts()) : the_post(); ?>
  //output post information here
<?php endwhile; ?>

you can switch on get_post_type() and display different information based on this.

<?php while (have_posts()) : the_post(); ?>
  if(get_post_type() == "custom_type")
  {
    //load custom fields and output here
  }
  else
  {
    //output normal post info here ala the_title(), the_excerpt(), etc...
  }
<?php endwhile; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM