2016-08-07 35 views
0

我正在開發一個wordpress站點,其中的帖子加載在彈出與ajax(與Magnific Popup)。帖子正在使用模板single.php加載Wordpress帖子沒有get_header()和get_footer()

這工作正常,除了頁眉和頁腳也加載在彈出(HTML標記,導航,腳本,...)。我當然可以從模板中刪除get_header()get_footer(),但是單個帖子頁面並未通過固定鏈接正確加載。

我嘗試了條件標籤,但是當模板使用Ajax加載時,它不會'看到'它被加載到主頁上。

我認爲使用不同的模板是一個選項,雖然我看到了使用相同模板(比如themeforest上的Zoo主題)的網站。但我無法弄清楚它在那裏的工作原理。

所以我卡在這裏。任何人?

+0

彈出窗口不夠真實,iframe或新的dom元素?我想如果你只是加載整個頁面來獲取內容很慢,你能不能運行你自己定製的ajax來提取內容? – David

+0

不確定如何描述彈出窗口;這是一個[Magnific Popup](http://dimsemenov.com/plugins/magnific-popup/),內容用ajax加載。整個頁面確實正在加載,這正是問題:如何加載循環? – user3782713

回答

1

乾淨的解決方案是使用WordPress的AJAX功能。

現在的主題通常會分成多個部分以在各個地方重複使用塊。例如,主題twentysixteen在single.php中使用get_template_part('template-parts/content', 'single');來包含顯示文件實際內容的模板文件。您可以輕鬆地使用它來獲取您的文章的內容,而無需標題,頁腳等。

首先,設置PHP部分,您可以將其添加到主題的functions.php中,或者直接添加到您的插件中你正在開發什麼。

<?php 
// for the admin area 
add_action('wp_ajax_my_action', 'my_action_callback'); 
// for the public area 
add_action('wp_ajax_nopriv_my_action', 'my_action_callback'); 

function my_action_callback() { 

    $postid = intval($_POST['postid']); 
    $post = get_post($postid); 
    setup_postdata($post); 
    get_template_part('template-parts/content', 'single'); 

    wp_die(); // this is required to terminate immediately and return a proper response 
} 

相應JavaScript部分:

var data = { 
    'action': 'my_action', 
    'postid': 1234 
}; 

// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php 
// on the frontend you have to set it yourself 
var ajaxurl = '<?=admin_url('admin-ajax.php')?>'; 
jQuery.post(ajaxurl, data, function(response) { 
    // alert('Got this from the server: ' + response); 
    // response will now contain your post, without header, footer, sidebars etc. 
}); 

my_action是整個過程的identifyer並且必須在兩個部件之間是一致的。

文檔WordPress的AJAX支持:https://codex.wordpress.org/AJAX_in_Plugins

+0

謝謝,現在我明白如何只拉內容而不是整個頁面而不使用其他模板或條件標籤。儘管我不太瞭解這裏的代碼,但我會盡力實現它 – user3782713

1

我終於找到了這個選項包含在Magnific Popup插件:「爲了它的加載後修改的內容,或選擇,並顯示從加載的文件只是特定元素,有是一個parseAjax回調「。

但我會接受上面的答案,因爲我認爲這是一種優雅的方式,而不是加載整個頁面,只顯示所需的部分。