|
<?php |
|
$query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 500 ) ); |
|
|
|
/** |
|
* Update post meta with IDs of URLs in post content. |
|
* |
|
* Uses post content links as related post. |
|
*/ |
|
foreach ( $query->posts as $post ) { |
|
$post_id = $post->ID; |
|
$content = $post->post_content; |
|
$url_ids = array(); |
|
// Get site URLs in post content. |
|
$urls = my_get_post_urls_in_content( $content ); |
|
|
|
foreach ( $urls as $url ) { |
|
// Attempt to get post ID from URL. |
|
$url_id = url_to_postid( $url ); |
|
// If ID is non-zero, add to array. |
|
if ( $url_id ) { |
|
$url_ids[] = $url_id; |
|
} |
|
// print_r( $url_ids ); |
|
// If using ACF field. |
|
// $update_field = update_field( 'related_posts', $url_ids, $post_id ); |
|
// If native CF. |
|
// $update_meta = update_post_meta( $post_id, 'related_posts', $url_ids ); |
|
} |
|
} |
|
|
|
/** |
|
* Extract interal (site) URLs from string (e.g., post content). |
|
* |
|
* @param string $content A string with URLs to extract. |
|
* @return array $urls An array of site URLs. |
|
*/ |
|
function my_get_post_urls_in_content( $content ) { |
|
$site_url = site_url(); |
|
// Make absolute URLs from relative URLs. |
|
$content = str_replace( 'href="/', "href=\"$site_url/", $content ); |
|
// Get arrray of URLs from content. |
|
$urls_all = wp_extract_urls( $content ); |
|
// Keep only URLs from this site. |
|
$urls = array_filter( $urls_all, function ( $var ) use ( $site_url ) { |
|
return ( strpos( $var, $site_url ) !== false ); |
|
}); |
|
|
|
return $urls; |
|
} |
|
?> |