In my wordpress website i create an Ajax search and search post_title. The code is here...
Function and script:
<?php
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: ajaxwpse.ajaxurl,
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('mobile','tablet') ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<li><?php the_title();?></li>
</div>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
After sucessfully search with Ajax Now i need to add post_title from search to div id="post-container" dynamically.
HTML
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search to add"></input>
<div id="datafetch"></div> // successfuly ajax Search Result Here
<div id="post-container"> </div> // Trying to add post title here
I create a ADD button in search result to add post_title into div.
How dynamically add post_title from search field to div with button?
You've to attach click event to your button the get the post_title and append it to the div :
$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();
$('#post-container').append( post_title );
});
});
Hope this helps.
$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();
if( $('#post-container p').length < 4 )
$('#post-container').append( '<p>' + post_title + ' ------ REMOVE</p>' );
else
alert('You could add max 4 titles');
});
$('body').on('click', '.remove-title', function(){
$(this).closest('p').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="post-link"> ADD </button>
<li>
The title 1 HERE
</li>
</div>
<div>
<button class="post-link"> ADD </button>
<li>
The title 2 HERE
</li>
</div>
<div>
<button class="post-link"> ADD </button>
<li>
The title 3 HERE
</li>
</div>
<hr>
<div id="post-container"> </div>
Compose both divs in your PHP function, then put them in a single <div>, like this:
PHP:
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('mobile','tablet') ) );
if( $the_query->have_posts() ) :
// compose $post_title
$post_title = "...";
echo "<div id=\"datafetch\">";
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<li><?php the_title();?></li>
</div>
<?php endwhile;
echo "</div><div id=\"post-container\">" . $post_title . "</div>";
wp_reset_postdata();
endif;
die();
}
HTML:
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search to add"></input>
<div id="result"></div>
JS:
// in your ajax call
success: function(data) {
jQuery('#result').html( data );
}
Related
I have a form:
<form method="get" action="/category/news/?newsSearch=" id="searchForm">
<input id="newsSearch" type="text" name="newsSearch" placeholder="Напишіть щось">
</form>
And I want to not refresh all page and just change this div
<div class="news" id="newsList">
<?php
global $post;
$postslist = get_posts( array( 'posts_per_page' => 200, 'category'=>'news' ) );
foreach ( $postslist as $post ){
setup_postdata($post);
?>
<div class="bl">
<div class="date">
<?php the_date(); ?>
</div>
<div class="tik">
<?php the_field('tiker'); ?>
</div>
<div class="price">
<?php the_field('price'); ?>
</div>
<div class="nnw">
<h5>
<a onclick="$('.hrs<?php the_ID(); ?>').slideToggle('slow');"><?php the_title(); ?> </a>
</h5>
<div class="src hrs<?php the_ID(); ?>">
<?php the_content(); ?>
<?php the_field('link'); ?>
</div>
</div>
<div class="site">
Сайт
</div>
</div>
<?php
}
wp_reset_postdata(); ?>
</div>
I find that solution Want to refresh a div after submit the form? but it didn't change anything (no console errors).
This is my variation of this script:
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='newsSearch']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#newsList" ).empty().append( content );
});
});
Form is changing URL to .../?newsSearch='query'and js is hiding posts that doesn't have query in their titles.
My code is working like charm but i need to add 2 dropdown into it:
this is where i input the value:
<form>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search..">
</form>
and i want it to look like this:
<form>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search..">
<select>
<option>location category</option>
<option>option2</option>
</select>
<select>
<option>category</option>
<option>option2</option>
</select>
</form>
i put this code in functions.php its working fine
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data:{ action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => 'locations'
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<div class="city-results">
<a href="<?php the_permalink();?>">
<h3>
<?php the_title();?>
</h3>
</a>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
?>
i guess we need to edit this area where fetching data
data:{ action: 'data_fetch', keyword: jQuery('#keyword').val() },
i tried using this Method but is not working :
data:{ action: 'data_fetch', keyword: jQuery('#keyword , #keyword2').val() },
but i'm noob in Jquery/Ajax
if anyone help me here with this Thanks in advance
You need to pass both dropdown values to the ajax data parameter. check the below code.
<form>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search..">
<select name="location" id="location">
<option>location category</option>
<option>option2</option>
</select>
<select name="category" id="category">
<option>category</option>
<option>option2</option>
</select>
</form>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data:{
action: 'data_fetch',
keyword: jQuery('#keyword').val(),
location: jQuery('#location').val(),
category: jQuery('#category').val()
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
echo $_POST['location']." ".$_POST['category'];
$the_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => 'locations'
)
);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<div class="city-results">
<a href="<?php the_permalink();?>">
<h3>
<?php the_title();?>
</h3>
</a>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
I set up an ajax load more button in Wordpress. How do I detect that there are no more posts to call and to not reload the same posts? On click it repeatedly grabs the last two posts and loads those. I was having an issue with when posts 3, 4, 5, and 6 were showing initially on the page then clicking the load more button it would call posts 3, 2, and 1 instead of just post 2 and 1. I added an offset of 4. That seems to fix that but it still calls the last two posts if I keep clicking load more. Also is there a way to hide the button if no more posts are detected?
// the pages post query
<?php
$args = array(
'post_type' => 'financial-news',
'post_status' => 'publish',
'posts_per_page' => '4',
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => 1,
);
?>
<?php $my_posts = new WP_Query( $args ); ?>
<?php if ( $my_posts->have_posts() ) : ?>
<?php $wp_query = new WP_Query(); $wp_query->query( $args ); ?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>
<div class="blog-post-wrapper one-column">
<div class="post-inner">
<div class="article-image"><img src="<?php the_field('thumb_image'); ?>"/></div>
<div class="article-copy match-height">
<span class="date"><?php the_time('F j, Y'); ?></span>
<h1><?php the_title(); ?></h1>
<p><?php echo wp_trim_words( get_the_content(), 25, '' ); ?></p>
<p><a class="read_more" href="<?php the_permalink(); ?>">Read More</a></p>
</div><!--article-copy-->
</div>
</div><!--blog-post-wrapper-->
<?php endwhile; ?>
</div><!--blog-content-->
<?php endif; ?>
<?php wp_reset_postdata(); // reset the query ?>
<div class="center-link"><div class="loadmore btn orange-btn-outline">Load More</div></div>
// The jS for the load button
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {
var post_type = 'financial-news';
var posts_per_page = 3;
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>',
'type' : 'post',
'post_type' : post_type,
'posts_per_page': posts_per_page,
};
$.post(ajaxurl, data, function(response) {
$('.blog-content').append(response);
page++;
});
});
});
// the functions.php code to load the posts
// blog load more button
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
$paged = $_POST['page'];
$post_type = $_POST['post_type'];
$posts_per_page = $_POST['posts_per_page'];
$lay_out = $_POST['lay_out'];
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $posts_per_page,
'offset' => 4,
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>
<div class="blog-post-wrapper" >
<div <?php post_class('post-inner'); ?> id="post-<?php the_ID(); ?>">
<div class="article-image"><img src="<?php the_field('thumb_image'); ?>"/></div>
<div class="article-copy match-height">
<span class="date"><?php the_time('F j, Y'); ?></span>
<h1><?php the_title(); ?></h1>
<p><?php echo wp_trim_words( get_the_content(), 25, '' ); ?></p>
<p><a class="read_more" href="<?php the_permalink(); ?>">Read More</a></p>
</div><!--article-copy-->
</div>
</div><!--blog-post-wrapper-->
<?php endwhile; ?>
<?php
endif;
wp_die();
}
i work on a project with woo.
On the mobile version of the site, the cart is a popup window.
When the customer adds many different products he must scroll down to see the buttons "view cart" "pay".
I try to add an autoscroll js code. When someone opens the cart it must scroll down automatically and stops at buttons "view cart" "pay".
I found some codes for "autoscroll to div" but none of them worked for me.
One simple js code i play with is this
$('#start').click(function() {
$('html,body').animate({
scrollTop: $('#bodycontainer').position().top
}, 1000 );});
but nothing happened.
Any help?
Thanks
You are trying to scroll the wrong thing, if it is the container that has the scroll. Replace it with this:
$('#start').click(function() {
$('#bodycontainer').animate({
scrollTop: 10000
}, 1000 );});
Now if you aren't using a container, then you may wish to add one.
I totally confused
My code for mini-cart is this
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
?>
<?php do_action( 'woocommerce_before_mini_cart' ); ?>
<div class="cart_list <?php echo esc_attr( $args['list_class'] ); ?>">
<?php if ( ! WC()->cart->is_empty() ) : ?>
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
$product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
$product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
$product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
?>
<div class="media widget-product">
<div class="media-left">
<a href="<?php echo esc_url( $product_permalink ); ?>" class="image pull-left">
<?php echo trim($thumbnail); ?>
</a>
</div>
<div class="cart-main-content media-body">
<h3 class="name">
<a href="<?php echo esc_url( $product_permalink ); ?>">
<?php echo trim($product_name); ?>
</a>
</h3>
<p class="cart-item">
<?php echo wc_get_formatted_cart_item_data( $cart_item ); ?>
<?php echo apply_filters( 'woocommerce_widget_cart_item_quantity', '<span class="quantity">' . sprintf( '%s × %s', $cart_item['quantity'], $product_price ) . '</span>', $cart_item, $cart_item_key ); ?>
</p>
<?php
echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
'×',
esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
__( 'Remove this item', 'opal_drop' ),
esc_attr( $product_id ),
esc_attr( $cart_item_key ),
esc_attr( $_product->get_sku() )
), $cart_item_key );
?>
</div>
</div>
<?php
}
}
?>
<?php else : ?>
<div class="empty"><?php esc_html_e( 'No products in the cart.', 'opal_drop' ); ?></div>
<?php endif; ?>
</div><!-- end product list -->
<?php if ( ! WC()->cart->is_empty() ) : ?>
<p class="total"><strong><?php esc_html_e( 'Subtotal', 'opal_drop' ); ?>:</strong> <?php echo WC()->cart->get_cart_subtotal(); ?></p>
<?php do_action( 'woocommerce_widget_shopping_cart_before_buttons' ); ?>
<p class="buttons clearfix">
<?php esc_html_e( 'View Cart', 'opal_drop' ); ?>
<?php esc_html_e( 'Checkout', 'opal_drop' ); ?>
</p>
<?php endif; ?>
<?php do_action( 'woocommerce_after_mini_cart' ); ?>
and i try this
jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({
scrollTop: $("#cart-main-content .media-body").offset().top
}, 2000);
}
});
With no luck. Now i practise with jquery
On my parent page, i have a custom page template calling another template:
if( have_posts() ): while( have_posts() ): the_post(); ?>
<div class="wrapper">
<?php get_template_part( 'template', 'page-section' ); ?>
<?php endwhile; endif; wp_reset_postdata(); ?>
Inside template-page-section.php, I have the following:
<?php
/*
Template Name: Page Section
*/
$args = array(
'post_parent' => 9,
'post_type' => 'page',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'order' => 'ASC'
);
$wpq = new WP_Query( $args ); ?>
<?php while ( $wpq->have_posts() ) : $wpq->the_post(); ?>
<?php if ( $post->ID == 101 ) {
include( 'template-slider.php' );
} ?>
<div class="page-section">
<h1><?php the_title(); ?></h1>
<?php /* The loop */ ?>
<?php the_content(); ?>
</div>
<?php endwhile; wp_reset_postdata();?>
Within the template-slider.php, is the following:
<div id="slider-container">
<ul id="slider">
<? $query = get_pages(
array(
'post_type' => 'slides',
'orderby' => 'menu_order',
'posts_per_page' => -1
));
foreach( $query as $post ) {
setup_postdata( $post ); ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail', $thumbsize[0] ); ?>
<li>
<img src="<?php echo $image[0]; ?>">
</li>
<?php } wp_reset_postdata(); ?>
</ul>
</div>
The issue is that once wordpress hits the loop within the slider-template, the information that it echos for the post content is not a child post of the parent, but the parents content.
Can anyone tell me what I'm doing wrong? I cant figure it out!
This is just an untested guess, but try the following:
template-page-section.php
$wpq = get_posts( $args );
if( $wpq ) {
foreach( $wpq as $p )
{
if ( $p->ID == 101 ) {
include( 'template-slider.php' );
}
?>
<div class="page-section">
<h1><?php echo $p->post_title; ?></h1>
<?php echo $p->post_content; ?>
</div>
<?php
}
}
template-slider.php
<div id="slider-container">
<ul id="slider">
<?php
$query_pages = get_pages(
array(
'post_type' => 'slides',
'orderby' => 'menu_order',
'posts_per_page' => -1
));
if( $query_pages )
{
foreach( $query_pages as $pg ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $pg->ID ), 'single-post-thumbnail', $thumbsize[0] ); ?>
<li>
<img src="<?php echo $image[0]; ?>">
</li><?php
}
} ?>
</ul>
</div>
Reference: When should you use WP_Query vs query_posts() vs get_posts()?