How do I count the number of views(Hits) in magento? Are there any built in methods available in magento?
EDIT from the comment:
I need total views for the entire site. I got the online users count from this code:
$visitor_count = Mage::getModel('log/visitor_online')
->prepare()
->getCollection()
->count();
if(!empty($visitor_count) && $visitor_count > 0) {
$cnt = $visitor_count;
echo 'Visitors online :'.$cnt;
}
The main table that you can use log_visitor
So, here is the code:
$totalUser = Mage::getSingleton('core/resource')->getConnection('core_write');
$queryTotal=$totalUser->query("SELECT * FROM log_visitor ORDER BY visitor_id DESC LIMIT 1 ");
// the result will give you maximum visitor_id
The problem with the code that you put in the top is that it will result in a table scan, which you probably don't want. Additionally, you don't want to be writing any SQL. So might want to try something like this in a block class.
$model = Mage::getModel('log/visitor_online');
$select = $model->getCollection()->getSelect();
/* #var $select Varien_Db_Select */
$select->reset(Varien_Db_Select::COLUMNS);
$select->columns(
new Zend_Db_Expr(
sprintf('count(%s)', $model->getIdFieldName())
)
);
echo $select->query()->fetchColumn(0);
Use this code to count like on per product place like button on product page , place this code in view.phtml
<?php
if (!is_dir('clickcounter')) {
#mkdir('clickcounter', 0777,true);
}
$filename=$_product->getSku().'.txt';
$dir='clickcounter' ;
if(!file_exists($dir.'/'.$filename)){
file_put_contents($dir.'/'.$filename, '0');
}
if(isset($_GET['click']) == 'yes'){
file_put_contents($dir.'/'.$filename, ((int) file_get_contents($dir.'/'.$filename)) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
?>
///// Ajax Update ///
function myAjax() {
jQuery.ajax({
type: "POST",
url: '?click=yes',
data:{action:'call_this'},
cache: false,
success: function (html) {
//location.reload(true);
jQuery(".favourite-img").replaceWith(jQuery('.favourite-img', jQuery(html)));
jQuery('#likeme').addClass('disabled');
}
});
}
</script>
//// HTML Code ///
<a id="likeme" class="disabled" href="javascript:void(0)" >
<div class="favourite-product">
<div class="favourite-img"><?php echo file_get_contents($dir.'/'.$filename); ?></div>
</div>
</a>
Related
I need help with my code as of now i have this
https://i.stack.imgur.com/b5yJL.png
this is my table, it wont display any row until someone will press the search button,. if they did it will display this
https://i.stack.imgur.com/9TpGG.png
a list of row from database with pages, my problem is when i click the page it will display like this
https://i.stack.imgur.com/6S4Nl.png it wont stay in the current page but redirect to the php files and i dont have any idea on what to do, the button is working btw, and it show the next right table in each page
here is my code for the page button
if($page>1)
{
echo "<a href='/api2/allrecords.php?page=".($page-1)."' class='btn btn-danger'>Previous</a>";
}
for($i=1;$i<$total_page;$i++)
{
echo "<a href='/api2/allrecords.php?page=".$i."' class='btn btn-primary'>$i</a>";
}
if($i>$page)
{
echo "<a href='/api2/allrecords.php?page=".($page+1)."' class='btn btn-danger'>Next</a>";
}
and here is for the sql
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$num_per_page = 20;
$start_from = ($page-1)*02;
$connect = mysqli_connect("127.0.0.1", "crudDBck69t", "NTCHilrXdf", "crudDBck69t");
$output = '';
$query = "
SELECT * FROM rvtable limit $start_from,$num_per_page
";
$pr_query = "select * from rvtable";
$pr_result = mysqli_query($connect,$pr_query);
$total_record = mysqli_num_rows($pr_result );
$total_page = ceil($total_record/$num_per_page);
$result = mysqli_query($connect, $query);
there are all in the same php files call
allrecord.php, but im displaying it on wordpress page.,
this is how i call it in my costume page template in wordpress
if(from_date == '' && to_date == '' && search == '') {
$.ajax({
url:"/api2/allrecords.php",
method:"POST",
data:{from_date:from_date, to_date:to_date, search:search},
success:function(data)
{
$('#rvoucher').html(data);
}
});
}
and its working well except the page button, should i change the link on it? but the $_GET is on allrecord.php file
any idea?
thanks
The problem you are having is that the POST data is not sent together with your GET request when the user clicks the link that is the next page button.
One solution could be to instead of using links where the href reloads the page use links that have a click event listener that would run your POST request again but only this time with the page selected.
Another thing, you shouldn't really be taking use input and putting it directly into your SQL queries as that exposes you solution to SQL injection
example of how to output buttons that should reload the table with the search data:
<script type="text/javascript">
function gotoPage(page) {
$.ajax({
url:"/api2/allrecords.php?page=" + page,
method:"POST",
data: {
from_date: atob("<?php echo base64_encode($_POST['from_date'] ?? ''); ?>"),
to_date: atob("<?php echo base64_encode($_POST['to_date'] ?? ''); ?>"),
search: atob("<?php echo base64_encode($_POST['search'] ?? ''); ?>"),
},
success: function(data) {
$('#rvoucher').html(data);
}
});
}
</script>
<?php
if ($page > 1) {
echo 'Previous';
}
for($i=1; $i < $total_page; $i++) {
echo '' . $i . '';
}
if($page < $total_page) {
echo 'Next';
}
?>
To begin with, I think this is a longshot but hopefully there is someone out there that can help.
To explain the current situation, at the moment I have a custom plugin that grabs various bits of information about a user and their 4 most recent posts.
I am also using the WPBook plugin (so this is on facebook and just just a typical wordpress site)
Ok, so here is my code that is grabbing the 4 most recent posts for a user:
// The Query
query_posts('posts_per_page=4&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// the Loop
while (have_posts()) : the_post();
?>
<div class="oe-grid-box">
<a href="<?php the_permalink() ?>" <?php the_title()?></a>
<div class="oe-grid-box-content">
<?php echo the_content( '...' ); ?>
</div>
<div class="oe-grid-pic">
<a href="<?php the_permalink() ?>">
<span class="<?php echo strtolower($category); ?>"></span>
</a>
<?php echo $image; ?>
</div>
</div>
<?php
endwhile;
// Reset Query
wp_reset_query();
?>
<div id="load-more">Load More</div>
I tried following this tutorial but instead of a separate plugin, placing the code in my existing plugin but now my page won't load:
http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/
Ideally, want I want to is when the load more button is clicked, fetch 4 more posts and show them.
If anybody could help I'd really appreciate it.
UPDATE
Ok,
so far I've added in my jQuery to call the php file which should hopefully return posts but it doesn't work.
I am thinking that it's because it doesn't know what the WordPress functions are?
If I put a simple echo in my load more script, the jQuery success function shows an alert to say it worked, but if I start doing WordPress stuff I get an internal server error, this is the code in the load-more.php file:
// load wordpress into template
$path = $_SERVER['DOCUMENT_ROOT'];
define('WP_USE_THEMES', false);
require($path .'/wp-load.php');
$blogger_id = $_GET['id'];
$firstname = $_GET['firstname'];
$surname = $_GET['surname'];
$posts = $_GET['posts'] + 4;
$category = $_GET['category'];
$image = $_GET['image'];
// The Query
query_posts('paged='.get_query_var('paged').'&posts_per_page=' . $posts . '&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// then the same loop as in my page that is making the ajax call.
After a lot of effort, I found the answer, here is a solution for those stuck in the same position.
This goes in your plugin page where you are getting posts for a user etc.
<script type="text/javascript">
$(document).ready(function() {
posts = 8;
author_posts = parseInt(<?php echo $author_posts; ?>);
$("#link_selector").click(function() {
// alert('posts - ' + posts + 'author posts - ' + author_posts);
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
else {
var category = '<?php echo strtolower($category); ?>';
var id = '<?php echo $blogger_id; ?>';
var firstname = '<?php echo $firstname; ?>';
var surname = '<?php echo $surname; ?>';
// alert(posts + category + id + firstname + surname);
$.ajax({
type: "GET",
url: "/wordpress/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'loadMore', id: id, firstname: firstname, surname: surname, posts: posts, category: category}),
success: function(data){
$('#ajax_results_container').hide().fadeIn('slow').html(data);
posts = posts + 4;
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
}
});
}
});
});
</script>
Then in your theme's functions.php, put your function to do your ajax request:
function loadMore() {
$blogger_id = $_GET['id'];
// get your $_GET variables sorted out
// setup your query to get what you want
query_posts('posts_per_page=' . $posts . '&author='.$blogger_id);
// initialsise your output
$output = '';
// the Loop
while (have_posts()) : the_post();
// define the structure of your posts markup
endwhile;
// Reset Query
wp_reset_query();
die($output);
}
Then, just after the closing of your function, put in the action hooks
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
That's it!
EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.
I am new with AJAX and JQuery. I am trying to use it to call two PHP scripts. I found some examples online but just to call functions. I am just trying to call the scripts so it will load everything on my main PHP file that will then be display on the screen the results withouth refreshing the page.
Here is the fiddle example, it works if I put all my PHP scripts in one file : http://jsfiddle.net/vw4w3ay5/
thanks in advance, your help is very much appreciated!
main_php file (where I want to call my other PHP scripts):
<div id="map_size" align="center">
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
display_desk.php (Script I want to call):
<?php
include 'db_conn.php';
//query to get X,Y coordinates from DB for the DESKS
$desk_coord_sql = "SELECT coordinate_id, x_coord, y_coord FROM coordinates";
$desk_coord_result = mysqli_query($conn,$desk_coord_sql);
//see if query is good
if($desk_coord_result === false) {
die(mysqli_error());
}
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
display_stationinfo.php(second script I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
echo "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
What about? :
<div id="map_size" align="center">
<?php
echo "<script>";
include "display_desk.php";
include "display_stationinfo.php";
echo "</script>";
?>
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
To be sure add $(document).ready(function(){
});
/EDIT/
Hum you want to use Ajax . did you try with :
$.post("yourURL.php",function(html){
/*here what you want to do*/
/*return of your script in html*/
});
To begin with, I think this is a longshot but hopefully there is someone out there that can help.
To explain the current situation, at the moment I have a custom plugin that grabs various bits of information about a user and their 4 most recent posts.
I am also using the WPBook plugin (so this is on facebook and just just a typical wordpress site)
Ok, so here is my code that is grabbing the 4 most recent posts for a user:
// The Query
query_posts('posts_per_page=4&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// the Loop
while (have_posts()) : the_post();
?>
<div class="oe-grid-box">
<a href="<?php the_permalink() ?>" <?php the_title()?></a>
<div class="oe-grid-box-content">
<?php echo the_content( '...' ); ?>
</div>
<div class="oe-grid-pic">
<a href="<?php the_permalink() ?>">
<span class="<?php echo strtolower($category); ?>"></span>
</a>
<?php echo $image; ?>
</div>
</div>
<?php
endwhile;
// Reset Query
wp_reset_query();
?>
<div id="load-more">Load More</div>
I tried following this tutorial but instead of a separate plugin, placing the code in my existing plugin but now my page won't load:
http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/
Ideally, want I want to is when the load more button is clicked, fetch 4 more posts and show them.
If anybody could help I'd really appreciate it.
UPDATE
Ok,
so far I've added in my jQuery to call the php file which should hopefully return posts but it doesn't work.
I am thinking that it's because it doesn't know what the WordPress functions are?
If I put a simple echo in my load more script, the jQuery success function shows an alert to say it worked, but if I start doing WordPress stuff I get an internal server error, this is the code in the load-more.php file:
// load wordpress into template
$path = $_SERVER['DOCUMENT_ROOT'];
define('WP_USE_THEMES', false);
require($path .'/wp-load.php');
$blogger_id = $_GET['id'];
$firstname = $_GET['firstname'];
$surname = $_GET['surname'];
$posts = $_GET['posts'] + 4;
$category = $_GET['category'];
$image = $_GET['image'];
// The Query
query_posts('paged='.get_query_var('paged').'&posts_per_page=' . $posts . '&author='.$blogger_id);
// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;
// then the same loop as in my page that is making the ajax call.
After a lot of effort, I found the answer, here is a solution for those stuck in the same position.
This goes in your plugin page where you are getting posts for a user etc.
<script type="text/javascript">
$(document).ready(function() {
posts = 8;
author_posts = parseInt(<?php echo $author_posts; ?>);
$("#link_selector").click(function() {
// alert('posts - ' + posts + 'author posts - ' + author_posts);
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
else {
var category = '<?php echo strtolower($category); ?>';
var id = '<?php echo $blogger_id; ?>';
var firstname = '<?php echo $firstname; ?>';
var surname = '<?php echo $surname; ?>';
// alert(posts + category + id + firstname + surname);
$.ajax({
type: "GET",
url: "/wordpress/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'loadMore', id: id, firstname: firstname, surname: surname, posts: posts, category: category}),
success: function(data){
$('#ajax_results_container').hide().fadeIn('slow').html(data);
posts = posts + 4;
if ((posts - author_posts) > 3) {
$("#link_selector").text('No more posts!');
}
}
});
}
});
});
</script>
Then in your theme's functions.php, put your function to do your ajax request:
function loadMore() {
$blogger_id = $_GET['id'];
// get your $_GET variables sorted out
// setup your query to get what you want
query_posts('posts_per_page=' . $posts . '&author='.$blogger_id);
// initialsise your output
$output = '';
// the Loop
while (have_posts()) : the_post();
// define the structure of your posts markup
endwhile;
// Reset Query
wp_reset_query();
die($output);
}
Then, just after the closing of your function, put in the action hooks
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
That's it!