正在檢視 5 個帖子:1-5 (共 5 個帖子)
-
作者帖子
-
環境簡述:
建立了一個多站點環境,改環境中 站點 id:318 的站管理所有的文章,目前希望在其他站透過 elementor post 的 custom query 直接獲取 318 站點中的文章,嘗試使用了 switch_to_blog(318) 獲取失敗請問,請教,請教!!
要在 WordPress 多站點環境中跨站點獲取文章,可以嘗試以下步驟:
- 在需要獲取文章的站點中,使用
switch_to_blog(318)
切換到 318 站點。 - 使用
WP_Query
或get_posts
函式來獲取 318 站點中的文章。 - 獲取完文章後,使用
restore_current_blog()
恢復到原始站點。
示例程式碼如下:
// 切換到 318 站點 switch_to_blog(318); // 查詢文章 $args = array( 'post_type' => 'post', 'posts_per_page' => 10, // 其他查詢引數 ); $query = new WP_Query($args); // 處理查詢結果 if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); // 輸出文章內容或其他操作 } } // 恢復到原始站點 restore_current_blog();
透過以上步驟,你應該能夠在其他站點中成功獲取 318 站點中的文章。如果仍然遇到問題,請檢查站點許可權、程式碼邏輯等方面是否有問題。
以上由殼殼蟲自動解答供參考,您可以繼續跟帖或等待人工回覆。
用簡碼呼叫吧,單純是這種用 elementor 的情況很難,需要用 API 來實現。
我們官網首頁呼叫的程式碼如下:
function get_latest_posts_titles_from_subsite($atts) { // 解析短程式碼引數 $atts = shortcode_atts(array( 'subsite_id' => 1, // 預設子站點 ID 'count' => 5, // 預設獲取 5 個文章標題 'post_type' => 'post', // 預設文章型別為 post ), $atts); // 獲取短程式碼引數中的子站點 ID 和文章型別 $subsite_id = intval($atts['subsite_id']); $post_type = $atts['post_type']; // 儲存當前主站點 ID $current_blog_id = get_current_blog_id(); // 使用 switch_to_blog 函式切換到特定子站點 switch_to_blog($subsite_id); // 構建 WP_Query 查詢 $args = array( 'posts_per_page' => intval($atts['count']), // 獲取指定數量的文章標題 'post_type' => $post_type, // 設定文章型別 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'ignore_sticky_posts' => 1, // 排除置頂文章 ); $query = new WP_Query($args); // 檢查是否有文章 if ($query->have_posts()) { $titles_list = '<ul>'; // 迴圈輸出文章標題 while ($query->have_posts()) { $query->the_post(); $titles_list .= '<li><a href="' . get_permalink() . '" target="_blank">' . get_the_title() . '</a></li>'; } $titles_list .= '</ul>'; // 切換回之前的主站點 switch_to_blog($current_blog_id); // 重置文章資料 wp_reset_postdata(); // 返回標題列表 return $titles_list; } else { // 切換回之前的主站點 switch_to_blog($current_blog_id); return ' 沒有找到最新文章。'; } } // 新增一個 shortcode 以便在文章或頁面中呼叫該函式 add_shortcode('latest_posts_titles', 'get_latest_posts_titles_from_subsite');
使用方式就是加簡碼
沒有找到最新文章。 );
$query->set( ‘category__in’, array( 12 ) );
// 恢復到原始站點
add_action(‘loop_end’, function() {
restore_current_blog();
});
});add_action(‘loop_end’, function() 最後這個是必須的不然會導致死迴圈,造成站點 504 。
測試在 elementor 元件中 post 可以用,但是 loop 的 post 模組無效!
你需要完全實現自定義文章型別查詢在後續的 WordPress 版本中這種方式容易導致網站負載增大,我上面給的方式可以測試下,完全從資料庫裡面直接讀取,不分編輯器版本不容易出錯,也沒那麼多額外查詢
- 在需要獲取文章的站點中,使用
-
作者帖子
正在檢視 5 個帖子:1-5 (共 5 個帖子)
- 哎呀,回覆話題必需登入。