Ani*_*ket 1 php regex wordpress
我正在更改博客的当前主题,并且希望在所有输入字段中添加一个类。
我不熟悉正则表达式代码,因此每当需要进行此类操作时,都会遇到很多麻烦。
我要添加类btn需要添加到<input type="submit">
旧密码
<input type="submit" id="some_id" name="something" class="some_class" value="some_value" />
Run Code Online (Sandbox Code Playgroud)
新密码
<input type="submit" id="some_id" name="something" class="btn some_class" value="some_value" />
Run Code Online (Sandbox Code Playgroud)
同样,我希望将类input添加到<input type="text">和<input type="textarea">
旧密码
<input type="text" id="some_id" name="something" class="some_class" value="some_value" />
<textarea id="some_id" name="something" class="some_class" value="some_value" />
Run Code Online (Sandbox Code Playgroud)
新密码
<input type="text" id="some_id" name="something" class="input some_class" value="some_value" />
<textarea id="some_id" name="something" class="input some_class" value="some_value" />
Run Code Online (Sandbox Code Playgroud)
考虑到您的限制,可以使用DOMDocument来最简单地使用PHP并在Wordpress框架内进行操作。尽管可能依赖于正则表达式,但是它很草率,而且您可能会遇到比开始时更多的问题。
将其放在您的functions.php文件中,它应该可以完成您需要的所有操作:
add_filter('the_content', 'add_text_input_classes', 20);
function add_text_input_classes($content)
{
$doc = new DOMDocument(); //Instantiate DOMDocument
$doc->loadHTML($content); //Load the Post/Page Content as HTML
$textareas = $doc->getElementsByTagName('textarea'); //Find all Textareas
$inputs = $doc->getElementsByTagName('input'); //Find all Inputs
foreach($textareas as $textarea)
{
append_attr_to_element($textarea, 'class', 'input');
}
foreach($inputs as $input)
{
$setClass = false;
if($input->getAttribute('type') === 'submit') //Is the input of type submit?
$setClass = 'btn';
else if($input->getAttribute('type') === 'text') //Is the input of type text?
$setClass = 'input';
if($setClass)
append_attr_to_element($input, 'class', $setClass);
}
return $doc->saveHTML(); //Return modified content as string
}
function append_attr_to_element(&$element, $attr, $value)
{
if($element->hasAttribute($attr)) //If the element has the specified attribute
{
$attrs = explode(' ', $element->getAttribute($attr)); //Explode existing values
if(!in_array($value, $attrs))
$attrs[] = $value; //Append the new value
$attrs = array_map('trim', array_filter($attrs)); //Clean existing values
$element->setAttribute($attr, implode(' ', $attrs)); //Set cleaned attribute
}
else
$element->setAttribute($attr, $value); //Set attribute
}
Run Code Online (Sandbox Code Playgroud)