-1

I would like to check if the hreflang attribute exists, I am not sure what the best method is? Is preg_match the only method or is there more?

function add_hreflang() {
    if( !($attribute['hreflang']) ){
        // do something
    }
}
add_action('wp_head', 'add_hreflang', 1);
Demian
  • 536
  • 5
  • 26

1 Answers1

0

you can use !empty() check

function add_hreflang() {
  if( !empty($attribute['hreflang']) ){
    // do something
  }
}

Edit: To check if any specific attribute is present you can use following code it converts your html element to xml object and then xml to array and find out if the attribute you need exists in the array. link to the orignal html to xml and xml to array code.

$str = '<a href="http://example.com" anotherAttrib="someValue">Link</a>';

$link = new SimpleXMLElement($str);
// print_r($link);

function xml2array( $xmlObject, $out = array () ){
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}


$arr = xml2array($link);
print_r($arr['@attributes']);
Umer Abbas
  • 1,866
  • 3
  • 13
  • 19
  • I have tested this, but does it also look if the `` is actually present? – Demian Mar 13 '20 at 16:57
  • @Demian please see the edited answer. – Umer Abbas Mar 13 '20 at 17:11
  • Okay that seems complex, but that only checks for that specific string? It cannot just check if `` element with attribute `hreflang` exists in the DOM? – Demian Mar 13 '20 at 17:18
  • I think that could be achieved with java script or jquery maybe. But with php you can not interact with DOM directly as it is a server side language and does not run in browser. – Umer Abbas Mar 13 '20 at 17:21
  • Read this https://stackoverflow.com/questions/2694640/find-an-element-in-dom-based-on-an-attribute-value – Umer Abbas Mar 13 '20 at 17:25
  • That makes sense. But I found the trigger here, your first suggestion with `!empty()` should be in this case `empty()`. So your first works without exclamation. Because my query `!($attribute['hreflang'])` the `!` = your `empty()`. – Demian Mar 13 '20 at 17:25