在这里,这应该足以让您入门。
首先你需要添加css、js元素到你的页面,你可以使用WordPress enqueue hook将它们分别添加到CSS和JS文件中,这只是一个基本的例子:
我将模态示例复制到:https://www.w3schools.com/howto/howto_css_modals.asp 以在此示例中使用。
function pop_up() {
?>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<div class="content-left">
<!-- Leave empty to be able to populate later with ajax -->
</div>
<div class="content-right">
<!-- Put your form here -->
</div>
</div>
</div>
<style>
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
<script>
jQuery(document).ready(function($) {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Let's do the magic
// make sure to change #myBtn to read more button selector
$(document).on("click","#myBtn",function(e) {
e.stopImmediatePropagation();
e.preventDefault();
// get url
var url = $(this).attr('href');
var container = $('#myModal').find('.content-left');
var data = {
action: 'show_product',
url: url,
};
$.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
// display the response
console.log(response);
$(container).empty();
$(container).html(response);
modal.style.display = "block";
});
});
});
</script>
<?php
}
add_action( 'wp_footer', 'pop_up' );
现在我们将根据 post 请求发送的 url 用 php 创建一个响应,您可以使用它来获取产品图像、内容、描述、价格或任何东西,并将它们放在一起以在 ajax 中以 HTML 形式返回响应以在模态中显示它
add_action('wp_ajax_show_product', 'show_product_callback_wp');
add_action( 'wp_ajax_nopriv_show_product', 'show_product_callback_wp' );
function show_product_callback_wp() {
$url = $_POST['url'];
$product_id = url_to_postid( $url );
// product content
$content_post = get_post($product_id);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$output = "";
$output .= get_the_post_thumbnail( $product_id, 'medium');;
$output .= $content;
echo $output;
exit();
}
这是经过测试和工作的。