Wordpress, add_filter, get_search_form

2019-06-03 14:43发布

I'm trying to replace the search form by my own.

An example plugin:

<?php
/*
Author: whatever
Plugin Name: Some Name
Plugin URI: 
Text Domain: some-domain
Version: 1.0
*/

function custom_search($form)
{
$form = "testing<form method = 'get' id = 'searchform' action = ' ".site_url()." ' >";
$form .= "<div><label class = 'hidden' for='s'>". __("Search for: ") . "</label>";
$form .= "<input type = 'text' value=' ". esc_attr(apply_filters('the_search_query', get_search_query())) ." ' name='s' id='s' />";
$form .= "<input type = 'submit' id='searchsubmit' value=' ".esc_attr(__('Look for it'))." ' />";
$form .= "</div>";
$form .= "</form>";

return $form;
}

add_filter('get_search_form', 'custom_search');

Result, doesn't work.

I'm using the latest Wordpress with twentyeleven theme.

What am I missing here?!?

EDIT: It appears that if the theme has searchform.php file, this filter will be overridden by that file. So basically filter only works if the theme doesn't have searchform.php. Now that is just stupid..

1条回答
我想做一个坏孩纸
2楼-- · 2019-06-03 15:47

This is a result of a well known WordPress bug in the get_search_form( $echo ) function will ignore the $echo argument and always echo jf you have a searchform.php template file in your theme.

It's a crap function, with a 2 year old trac ticket. Until they fix it, there are few workarounds: 1. Use file_get_contents() - but won't parse the PHP 2. Use custom function with the get_searchform hook (not the actual function) 3. Or use simple output buffering to capture the output as a variable;

This page has examples for all 3 methods

查看更多
登录 后发表回答