Add html to wp_login_form

时间:2016-10-12 作者:kiarashi

在模板中

<?php wp_login_form( array( \'echo\' => true ) ); ?>
源代码

<p class="login-remember">
<label>
<input name="rememberme" type="checkbox" id="rememberme" value="forever"> Remember Me
</label>
</p>
我想在后面添加一个span标记Remember me

Remember Me <span class="custom-styled-checkbox"></span>
我试图向标签中添加一些html,但没有成功:

    $args = array(                  
    \'label_remember\' => __( \'Remember Me <span class="custom-styled-checkbox"></span>\' ),
        );
   wp_login_form( $args );
也没做过这么简单的事

function custom_checkbox_form($output) {
    $search  = array(\'<p class="login-remember"><label>\',\'</label></p>\');
    $replace = array(\'<p class="login-remember"><label>\', \'<span class="custom-styled-checkbox"></span></label></p>\'); 

    return str_replace( $search, $replace, $output );
}   
add_filter( \'login_head\', \'custom_checkbox_form\', 99, 1 );
非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:Dave Romsey 整理而成

这个label_remember 论点仅用于更改文本;HTML将被转义,因此在这里不起作用。

相反,登录表单的HTML可以在输出之前进行解析和修改:

// Get the HTML for the login form
$login_form = wp_login_form( [ \'echo\' => false ] );

// Create an instance of DOMDocument 
$dom = new \\DOMDocument();

// Populate $dom with our login form, making sure to handle UTF-8, otherwise
// problems will occur with UTF-8 characters.
$dom->loadHTML( mb_convert_encoding( $login_form, \'HTML-ENTITIES\', \'UTF-8\' ) );

// Create an instance of DOMXpath and get the <p class="login-remember"> node
$xpath = new \\DOMXpath( $dom );
$remember = $xpath->query( \'//p[@class="login-remember"]\' );

// Iterate over the $remember node...
foreach ( $remember as $container ) {
    // Create the <span> element
    $checkbox_span = $dom->createElement( \'span\' );

    // Create the class attribute
    $checkbox_span_attr = $dom->createAttribute( \'class\' );
    // Set the value of the class attribute
    $checkbox_span_attr->value = \'custom-styled-checkbox\';

    // Add class="custom-styled-checkbox" to the <span> element
    $checkbox_span->appendChild( $checkbox_span_attr );

    // Append the completed <span class="custom-styled-checkbox"></span> element
    // to <p class="login-remember"><label>
    //$container->childNodes[0]->appendChild( $checkbox_span ); // Fails on PHP < 5.6.3?
    $container->childNodes->item(0)->appendChild( $checkbox_span );
}

// Save the updated HTML to $login_form and output it.
$login_form = $dom->saveHTML();
echo $login_form;