Как показать последние сообщения в основном домене из блога поддоменов
Нужно показать последнее сообщение с моего субдомена на мой основной домен. Я использую приведенный ниже код, но он выбирает только основной домен недавний пост. любая помощь, чтобы получить поддомен недавнего сообщения?
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
1 ответ
РЕДАКТИРОВАТЬ 2:
Таким образом, получается, что вы не используете оба сайта из одной и той же установки WordPress (иначе называемой WordPress Network). Вот что я могу предложить, чтобы вы использовали в этом случае.
Поместите этот код в основной сайт functions.php
:
/**
* this function retrieves the requested part of the main site
* ok, well basically can be from any site, depending on the $url param, as long as it has the proper function that will display the requested content
* @param $url - the url of the site
* @param $key - part of the name of the function that will display the content
* @param $add_qs - any additional query string that will be appended, use "¶ms=param1,param2,param3" to pass "param1", "param2" and "param3"
* to the loading function
*/
function get_main_site_part($url, $key, $add_qs = '') {
// cache the result, so we don't make a request with each page load
$cache = ABSPATH . 'wp-content/uploads/main_site_' . $key . '.txt';
$cache_lifetime = 300;
// just to make sure - try to remove the trailing slash in the $url
$url = untrailingslashit($url);
$uri = $url . '/?including_template_part=1&load_part=' . $key . $add_qs;
# reload the cache on every 5 minutes
if (!file_exists($cache) || time() - filemtime($cache) > $cache_lifetime) {
$main_site_html = wp_remote_get($uri);
if (is_a($main_site_html, 'WP_Error')) {
//print_r($main_site_html);
//exit('error! ');
return;
}
$fp = fopen($cache, 'w');
fwrite($fp, $main_site_html);
fclose($fp);
} else {
$main_site_html = file_get_contents($cache);
}
return $main_site_html;
}
Теперь поместите эту функцию в свой поддомен functions.php
:
/* HTML LOADING HOOK - For loading content from one site to another - best application in multisite */
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] && $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
Затем на вашем главном сайте вызовите эту функцию, где вы хотите, чтобы ваши последние сообщения появлялись:
echo get_main_site_part( 'http://questions.admissiontimes.com/', 'my_recent_posts', '¶ms=5' )
РЕДАКТИРОВАТЬ 1:
Используя пример кода, который у вас есть в вашем вопросе, в сочетании с моим решением ниже, вот как будет выглядеть окончательный код:
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts from. You can see the ID when you edit a site through the Network Admin - the URL will look something like "http://example.com/wp-admin/network/site-info.php?id=2" - you need the value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
Теперь вы просто помещаете этот код туда, где у вас был исходный код, и все должно работать правильно.
Вам нужно переключиться на рассматриваемый блог, используя switch_to_blog($blog_id)
функция, где $blog_id
идентификатор блога (под-сайта), о котором идет речь.
Затем выполните обычную функцию get_posts / или эквивалентную / и отобразите / сохраните сообщения так, как вы хотите.
Как только вы закончите с этим, просто позвоните restore_current_blog()
и это все.