#javascript #wordpress #magnific-popup
#javascript #wordpress #magnific-popup
Вопрос:
Я пытаюсь загрузить magnific-popup в свою тему, однако это не работает, и я не уверен, почему. Когда я нажимаю на изображение, оно просто показывает стандартное необработанное изображение.
Когда я создавал это только в html, это работало нормально, однако в WordPress это, похоже, не работает.
Я протестировал оба main.js и jquery.magnific-popup.min.js с предупреждением («привет»); и оба они выдают предупреждение, так что оба они работают.
Мои файлы в очереди кажутся правильными, хотя я не уверен, что использую правильные функции ‘the_post_thumbnail_url ();’ здесь в моем шаблоне страницы для ссылки на изображение?
Кто-нибудь может заметить проблему?
К вашему сведению: я не хочу использовать плагин.
изображение моего каталога
файлы в очереди
function add_theme_scripts()
{
wp_enqueue_style('magnific-popup', get_stylesheet_uri() . '/assets/css/magnific-popup/magnific-popup.css', true);
wp_enqueue_style('style', get_stylesheet_uri());
wp_enqueue_script('jquery-3.5.1', get_template_directory_uri() . '/assets/js/jquery-3.5.1.min.js', '3.5.1', true); /*when uploaded to server, wordpress already has jquery*/
wp_enqueue_script('magnific-popup', get_template_directory_uri() . '/assets/js/magnific-popup/jquery.magnific-popup.min.js', '1.1.0', true);
wp_enqueue_script('main', get_template_directory_uri() . '/assets/js/main.js', true);
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
мой page-project.php
<?php
/**
* Template Name: Project Page
* Template Post Type: post
*/
get_header();
?>
<div class="content">
<h1 class="title main-title"><?php the_title(); ?></h2>
<?php if (have_posts()) : while (have_posts()) : the_post();
the_content();
endwhile;
endif; ?>
<?php
$projects = new WP_Query(array(
'posts_per_page' => 5,
'post_type' => 'projects',
)); ?>
<div class="the-content">
<?php if ($projects->have_posts()) : while ($projects->have_posts()) : $projects->the_post(); ?>
<div class="post-content">
<div class="project-images">
<?php if (has_post_thumbnail()) : ?>
<a class="popup" href="<?php the_post_thumbnail_url(); ?>">
<img src="<?php the_post_thumbnail_url(); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" />
</a>
<?php endif; ?>
</div>
<h2 class="title"><?php the_title(); ?></h2>
<?php endwhile;
else : _e('Sorry, no posts seem to have been found');
endif; ?>
</div>
</div>
<div class="step-back">
<a href="<?php echo site_url('/'); ?>">home</a></p>
</div>
js-файл из main.js
// magnific popup
jQuery('.project-images').magnificPopup({
delegate: 'a',
type: 'image',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 3], // Will preload 0 - before current, and 1 after the current image
tPrev: 'Previous', // title for left button
tNext: 'Next', // title for right button
},
removalDelay: 300,
closeOnContentClick: true,
midClick: true,
mainClass: 'mfp-fade',
callbacks: {
buildControls: function () {
// re-appends controls inside the main container
this.contentContainer.append(this.arrowLeft.add(this.arrowRight));
}
}
});
Комментарии:
1. В ваших сценариях постановки в очередь вы не указываете местоположение скриптов, которые хотите использовать в качестве зависимостей, а указываете дескриптор скрипта. Итак, поскольку вы добавляете
jquery-3.5.1
, это должно быть вашей зависимостью.array('jquery-3.5.1')
2. Это не работает для меня, это делает предварительный загрузчик сайта в бесконечном цикле!
3. Однако это не решает мою проблему…
4. Я заметил, что ваш цикл while заканчивается перед закрытием div для содержимого — поместите его в свой цикл после h2
5. Что делать, если в консоли отображаются какие-либо ошибки
Ответ №1:
У меня была эта проблема, когда всплывающее окно не работало, и для меня это оказалось конфликтом jQuery. Оказывается, мне нужно было использовать другую версию jQuery. Вот что сработало для меня.
После добавления magnific-popup.min.css мне пришлось отменить регистрацию существующего jQuery и поставить в очередь версию 3.5.1. Обратите внимание, что зависимость — jquery. Вот ссылка на документацию.
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', get_template_directory_uri() . '/js/jquery3.js');
wp_enqueue_script( 'jquery', get_template_directory_uri() . '/js/jquery3.js');
wp_enqueue_script( 'magnific-popup', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js', array('jquery'), '', true );
wp_enqueue_script( 'magnific-popup-init', get_template_directory_uri() . '/js/jquery.magnific-popup.init.js', array('jquery'), '', true );
wp_enqueue_script( 'custom', get_template_directory_uri() . '/js/custom.js', array('jquery'), '', true );