I am trying to return all the links inside my posts'/pages' content, but I can't figure out how to get my regex/loop to work right. Here is what I have at the moment, that just returns a bunch of empty arrays when I print_r($matches). Any suggestions are greatly appreciated. Let me know if I need to provide more details.

function find_all_links() {
    // Let's get the posts
    $the_query = new WP_Query( array( 
        'posts_per_page'   => -1,  
    ) );
    if ( $the_query->have_posts() ) {

        // Start a list
        $results = '<br><ul>';

        // For each list item...
        while ( $the_query->have_posts() ) {

            // Get the post

            // Get the post content
            $content = get_the_content();

            preg_match_all("/<a\s[^>]*href\s*=\s*([\"\']??)([^\"\' >]*?)\\1[^>]*>(.*)<\/a>/siU", $content, $matches, PREG_SET_ORDER);

            if (!empty($matches)) {
                foreach ($matches as $match) {
                    $results .= '<li> '.$match.' (<a href="'.get_the_permalink().'" target="_blank">' . get_the_title() . '</a>)</li>';

        // End the list
        $results .= '</ul>';
    } else {
        // no posts found
        $results = 'No posts found.';

    // Restore original Post Data

    return $results;

1 Answer 1


After further investigation, I noticed my theme was actually replacing all the anchor tags with shortcodes for SEO purposes, so there weren't any links in the content anymore. I was able to make it work by replacing

$content = get_the_content();


$content = apply_filters( 'the_content', get_the_content() );

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.