-1

I am writing this because I am confused about whether it is possible to read the head tags when I'm in admin.

Searching for queries like "reading wordpress" return how to add code to header, but my intention is to check whether there are certain link tags inside my not to add any.

How can I achieve this?

3
  • You can use DevTools or view page source to see what you have between <head></head> Nov 20, 2022 at 11:31
  • I know, but I need to get these inside code. I have a relationship schema for a multisite and I need to read the head to see if there is <link> tag that contains my relationship and do stuff later on based on that.
    – tearswep
    Nov 20, 2022 at 11:38
  • Well most functions hook into wp_head in a way, some directly, others use different hooks that use wp_head. You can start with looking into wp_head Nov 20, 2022 at 11:44

1 Answer 1

0

If you're in the admin and you want to "read" the <head /> of the frontend, you can make an internal HTTP request and scrape the response HTML:

$url = home_url();

$request = wp_remote_get( $url );

$body = wp_remote_retrieve_body( $request );

$dom = new DOMDocument();

libxml_use_internal_errors( true );

$dom->loadHTML( $body );

$xpath = new DOMXpath( $dom );

$links = $xpath->query( '/html/head/link[@rel="stylesheet"]' );

foreach ( $links as $link ) {
    echo $link->getAttribute( 'href' );
    echo "\n";
}

This is just example code as I don't know what exactly you're looking for - you might want to change $url to be a specific post permalink (instead of the homepage), or you might want to change the DOM xpath to query the link tag you're looking for directly by its attribute.

4
  • Wouldn't that cause an infinite loop?, you do a get request to home url, that in turn will trigger this code, this code does a get request to home, home triggers this code, etc. Is that not the case? Nov 20, 2022 at 12:55
  • It doesn't cause an infinite loop @Buttered_Toast , just tested it out with admin_init hook.
    – tearswep
    Nov 20, 2022 at 13:36
  • @TheDeadMedic , what hook would you recommend to read the styles from a post in admin area? I've used admin_init, but it doesn't take seem to wait for all the styles to load. My goal is to get to a post in admin area, check whether the post has a <link hreflang="example-locales"> and get those locales to update the posts programatically later on.
    – tearswep
    Nov 20, 2022 at 13:42
  • @tearswep The hook depends on what & when you want to do the checks. If this is something you want to do regularly (& automated i.e. without user action) it might be better suited for a recurring WP cron event Nov 21, 2022 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.