【问题标题】:How to insert a span inside a search form? (Genesis)如何在搜索表单中插入跨度? (创世纪)
【发布时间】:2017-03-12 15:22:10
【问题描述】:

当我调用genesis_search_form() 时,它会输出:

<form class="search-form">
  <meta itemprop="target">
  <input type="search">
  <input type="submit">
</form>

但我希望它在内部生成 span,例如:

<form class="search-form">
  <meta itemprop="target">
  <input type="search">
  <span class="submit-icon"></span>
  <input type="submit">
</form>

正在寻找更安全的替代方案:

add_filter( 'genesis_search_form', 'my_search_button' ); 
function my_search_button( $form ) {
    return str_replace( 
        '<input type="submit"', 
        '<span class="submit-icon"></span><input type="submit"', 
        $form 
    );
}

为了避免替换标签的开头。有什么想法吗?

【问题讨论】:

  • 只要该功能不提供执行此操作的能力,您将无法执行此操作,如果允许分叉该功能并根据您的需要对其进行自定义需要。

标签: php wordpress search genesis search-form


【解决方案1】:

如果允许您对函数进行更改,请执行此操作。如果没有,请破解它!

$('form.search-form input[type=search]').after('<span class="submit-icon"></span>');

【讨论】:

  • 感谢您的回答,jQuery 确实更简单,但正在寻找解决方案在php 做所有服务器端。
【解决方案2】:

如果你对 DOMDocument 没问题,这个版本更适合 HTML5。

add_filter( 'genesis_search_form', 'my_search_button' );
function my_search_button($form) {

    $document = new DOMDocument();
    $document->loadHTML($form);
    $xpath = new DOMXPath($document);
    $input = $xpath->query('//input[@type="submit"]');
    $span = $document->createElement('span');
    $span->setAttribute('class', 'sb-icon');

    if ($input->length > 0) {
        $input->item(0)->parentNode->insertBefore($span, $input->item(0));
    }

    $document->removeChild($document->doctype); 
    $document->replaceChild($document->firstChild->firstChild->firstChild, $document->firstChild);
    $form_html = $document->saveHTML();

    return $form_html;
}

【讨论】:

    【解决方案3】:

    使用 DOMDocument!这是您的代码的工作版本: https://3v4l.org/ats7D

    <?php
    
    // Create a DOM Document
    $dom = new DomDocument();
    
    // Load your HTML
    $dom->loadHTML('<form class="search-form">  
        <meta itemprop="target">
        <input type="search">
        <input type="submit">
    </form>');
    
    // Create a new <span>
    $span = $dom->createElement('span', 'hello');
    
    // Grab the <input elements (we dont have an ID)
    $inputs  = $dom->getElementsByTagName('input');
    
    // Add the <span> between the inputs 
    $inputs->item(0)->parentNode->insertBefore($span, $inputs->item(1));
    
    // By default when you loadHTML(), it generates doctype, html, head, and     body tags. remove them!
    $dom->removeChild($dom->doctype);
    $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);
    
    // Finally get the HTML
    $html = $dom->saveHTML();
    
    // And output / return / whatever
    echo $html;
    

    【讨论】:

    • 太棒了;它可以让您将其保留在服务器端,就像他想要的那样。以某种方式缓存结果也可能有意义,这样他就不必在每个请求中操作 DOM 块。
    猜你喜欢
    • 2021-09-30
    • 2016-06-22
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多