I have button "Show more" on my WP site. By default 2 posts are shown, and on click on this button appears other 2 posts. So I need to check on page load, if there is more than 2 posts. It there is not, button hides. I use AJAX for this. But my code doesn't work.
functions.php
function buttonHide() {
$posts_count = wp_count_posts()->publish;
if ($posts_count <= 2) {
echo '<script>function hideLoadMore(){$("#load-post").hide();}</script>';
}
// Reset Query
wp_reset_query();
die();
}
add_action('wp_ajax_buttonHide', 'buttonHide');
add_action('wp_ajax_nopriv_buttonHide', 'buttonHide');
load.js
$(function() {
checkLoadButton();
function checkLoadButton() {
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: ({
action: 'buttonHide'
}),
type: "GET",
success: function() {
if (hideLoadMore) {
hideLoadMore(); //function from functions.php
}
}
});
}
});
Check this
functions.php
function buttonHide() {
$posts_count = wp_count_posts()->publish;
if ($posts_count <= 2) {
$result['type'] = "success";
$result['status'] = 'hide' ;
$result = json_encode($result);
echo $result;
die();
}else{
$result['type'] = "success";
$result['status'] = 'show' ;
$result = json_encode($result);
echo $result;
die();
}
die();
}
add_action('wp_ajax_buttonHide', 'buttonHide');
add_action('wp_ajax_nopriv_buttonHide', 'buttonHide');
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_localize_script( 'more_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'more_script' );
}
load.js
function checkLoadButton() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "buttonHide"},
success: function(response) {
if(response.type == "success") {
if(response.status=="hide"){
jQuery("#load-post").hide();
}else if(response.status=="show"){
jQuery("#load-post").show();
}
}
else {
alert("Error")
}
}
});
}
$(function() {
checkLoadButton();
});
Your variable hideLoadMore is indeed not defined.
If you expect this variable to be the response to your Ajax, you should correct your callback-function:
$(function() {
checkLoadButton();
function checkLoadButton() {
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: ({
action: 'buttonHide'
}),
type: "GET",
success: function(response) {
if (response) {
hideLoadMore(); //function from functions.php
}
}
});
}
});
If you want to get an function as result, you have to use JSONP as accept: -option in your AJAX