Last active
December 14, 2015 23:38
-
-
Save wokamoto/5166821 to your computer and use it in GitHub Desktop.
[WordPress][PHP] Google Search API で関連記事を取得するサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include('/path/to/wordpress/wp-load.php'); | |
$post_id_org = 2895; // post ID | |
// get keywords | |
$keywords = array(); | |
$tags_categories = get_the_terms($post_id_org, array('post_tag','category')); | |
foreach ($tags_categories as $val) { | |
if ( in_array($val->name, $keywords) ) | |
continue; | |
$keywords[] = $val->name; | |
} | |
unset($tags_categories); | |
// get related posts | |
$related_posts = get_related_posts($keywords, 0, 8); | |
foreach ( $related_posts as $post_id => $post ) { | |
if ( $post_id === $post_id_org ) | |
continue; | |
$permalink = get_permalink($post_id); | |
echo "{$post_id} : {$post->post_title} {$permalink}\n"; | |
} | |
// get related posts from Google Search API | |
function get_related_posts($keywords, $start = 0, $max = 8) { | |
$related_posts = array(); | |
$site = trailingslashit(get_home_url()); | |
$gs_url = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%1$s&rsz=%2$d&start=%3$d'; | |
$gs_query = sprintf('site:%1$s ("%2$s")', $site, implode('" OR "', $keywords)); | |
$response = wp_remote_get(sprintf($gs_url, urlencode($gs_query), $max, $start)); | |
if ( !is_wp_error($response) && $response['response']['code'] == 200) { | |
$results = json_decode($response['body'])->responseData->results; | |
foreach ($results as $result) { | |
$post_id = intval(url_to_postid($result->url)); | |
if ( !$post_id ) | |
continue; | |
$related_posts[$post_id] = get_post($post_id); | |
} | |
} | |
unset($response); | |
return $related_posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment