У меня есть код для отображения случайной цитаты. Один человек написал функцию для реализации всего этого. Но данные об обновлении через Ajax по какой -то причине не работают. Когда вы нажимаете кнопку «Новая цитата», ничего не происходит. Может, кто -то знает, почему? Что нужно исправить в следующем коде, так что при нажатии «Новая цитата» новая цитата загружается?
/wp-content/themes/%your_theme%/js/ajax-load-quote.php< /code> < /p>
< /code>
html -структура < /h2>
В содержании страницы, виджет или файл шаблона: < /p>
I would rather have my ignorance than another man’s knowledge,
because I have so much more of it.
-- Mark Twain, American author & Playwright
New Quote
< /code>
Это, очевидно, вы можете приспособиться к своему вкусу, но ради этого примера это то, что мы идем.
мы Сгенерирует вышеуказанное через короткометражный код./wp-content/themes/%your_theme%/js/ajax-load-quote.js< /code> < /p>
function ajaxQuote() {
var theQuote = jQuery.ajax({
type: 'POST',
url: ajaxParams.themeURI+'js/ajax-load-quote.php',
/* supplying the file path to the ajax loaded php as a $_POST variable */
data: { file_path: ajaxParams.filePath },
beforeSend: function() {
ajaxLoadingScreen(true,'#randomquotes');
},
success: function(data) {
jQuery('#randomquotes').find('p').remove();
jQuery('#randomquotes').prepend(data);
},
complete: function() {
ajaxLoadingScreen(false,'#randomquotes');
}
});
return theQuote;
}
/* Loading screen to be displayed during the process, optional */
function ajaxLoadingScreen(switchOn,element) {
/* show loading screen */
if (switchOn) {
jQuery(''+element).css({
'position': 'relative'
});
var appendHTML = '
';
if( jQuery(''+element).children('.ajax-loading-screen').length === 0 ) {
jQuery(''+element).append(appendHTML);
}
jQuery(''+element).children('.ajax-loading-screen').first().css({
'display': 'block',
'visibility': 'visible',
'filter': 'alpha(opacity=100)',
'-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"',
'opacity': '1'
});
} else {
/* hide the loading screen */
jQuery(''+element).children('.ajax-loading-screen').css({
'display': '',
'visibility': '',
'filter': '',
'-ms-filter': '',
'opacity': ''
});
jQuery(''+element).css({
'position': ''
});
}
}
/* triggering the above via the click event */
jQuery('#newquotes').click( function() {
var theQuote = ajaxQuote();
return false;
});
< /code>
функциональный/wp-content/themes/%your_theme%/functions.php< /code> < /p>
function random_quote( $atts ) {
/* extracts the value of shortcode argument path */
extract( shortcode_atts( array(
'path' => get_template_directory_uri() . '/quotes.txt' // default, if not set
), $atts ) );
$array = file( $path );
$r = rand( 0, count($array) - 1 );
$output = '' .
'
' . $array[$r] . '
' .
'' .
'New Quote';
/* enqueue the below registered script, if needed */
wp_enqueue_script( 'ajax-quote' );
/* supplying the file path to the script */
wp_localize_script(
'ajax-quote',
'ajaxParams',
array(
'filePath' => $path,
'themeURI' => get_template_directory_uri() . '/'
)
);
return $output;
}
add_shortcode( 'randomquotes', 'random_quote');
/* register the js */
function wpse72974_load_scripts() {
if ( ! is_admin() ) {
wp_register_script(
'ajax-quote',
get_template_directory_uri() . '/js/ajax-load-quote.js',
array( 'jquery' ),
'1.0',
true
);
}
}
add_action ( 'init', 'wpse72974_load_scripts' );
< /code>
Как вы можете обновить контент на странице, используя Ajax в WordPress?
Подробнее здесь: https://stackoverflow.com/questions/134 ... -shortcode
Как использовать Ajax в шорткоде WordPress? ⇐ Php
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Отображать только товары «на складе» в шорткоде «Последние продукты» Woocommerce.
Anonymous » » в форуме Php - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Отображать только товары «на складе» в шорткоде «Последние продукты» Woocommerce.
Anonymous » » в форуме Php - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-