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!
Related
I have this code, which allows me to make a "show more" button on Advanced Fields Pro repeater Elements in WordPress.
The problem is when I click fast twice(or more) on the buttons it shows me the fields, which are hidden also twice the (or more) time.
Does anyone have an idea on how to solve it?
Code on WordPress Front end:
<div id="photo-gallery">
<div class="row mt-5 mb-3">
<?php
if( have_rows('logos_der_externen_plattformen') ):
$total = count(get_field('logos_der_externen_plattformen'));
$count = 0;
$number = 5;
while ( have_rows('logos_der_externen_plattformen') ) : the_row(); ?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img data-src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="lazy img-fluid">
</div>
<?php
if ($count == $number) {
// we've shown the number, break out of loop
break;
} ?>
<?php $count++; endwhile;
else : endif;
?>
</div>
<div align="center" class="text-decoration-none">
<a id="gallery-load-more" style="text-decoration:none;" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> class="d-none" <?php } ?>><h7 id="title-bg"><span>und viele mehr...</span></h7></a></div>
</div>
var my_repeater_field_post_id = <?php echo $post->ID; ?>;
var my_repeater_field_offset = <?php echo $number + 1; ?>;
var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
var my_repeater_more = true;
function my_repeater_show_more() {
// make ajax request
jQuery.post(
my_repeater_ajax_url, {
// this is the AJAX action we set up in PHP
'action': 'my_repeater_show_more',
'post_id': my_repeater_field_post_id,
'offset': my_repeater_field_offset,
'nonce': my_repeater_field_nonce
},
function (json) {
// add content to container
// this ID must match the containter
// you want to append content to
jQuery('#photo-gallery .row').append(json['content']);
// update offset
my_repeater_field_offset = json['offset'];
// see if there is more, if not then hide the more link
if (!json['more']) {
// this ID must match the id of the show more link
jQuery('#gallery-load-more').css('display', 'none');
}
},
'json'
);
}
Backend:
/**
* ACF Load More Repeater
*/
// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');
function my_repeater_show_more() {
// validate the nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
exit;
}
// make sure we have the other values
if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
return;
}
$show = 10; // how many more to show
$start = $_POST['offset'];
$end = $start+$show;
$post_id = $_POST['post_id'];
// use an object buffer to capture the html output
// alternately you could create a varaible like $html
// and add the content to this string, but I find
// object buffers make the code easier to work with
ob_start();
if (have_rows('logos_der_externen_plattformen', $post_id)) {
$total = count(get_field('logos_der_externen_plattformen', $post_id));
$count = 0;
while (have_rows('logos_der_externen_plattformen', $post_id)) {
the_row();
if ($count < $start) {
// we have not gotten to where
// we need to start showing
// increment count and continue
$count++;
continue;
}
?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="img-fluid">
</div>
<?php
$count++;
if ($count == $end) {
// we have shown the number, break out of loop
break;
}
} // end while have rows
} // end if have rows
$content = ob_get_clean();
// check to see if we have shown the last item
$more = false;
if ($total > $count) {
$more = true;
}
// output our 3 values as a json encoded array
echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
exit;
} // end function my_repeater_show_more
This solution fork just fine for me:
document.getElementById("title-bg").onclick = function() {
document.getElementById("title-bg").style.display = "none";
}
There are 2 ways you could solve this:
Create a wrapper function around your JAVASCRIPT implementation of my_repeater_show_more. When this function starts, set a variable that the request is in progress. Unset the variable when the request has completed and the fields have been loaded. Disable the button when the field is set. This way, while the fields are loading, the button cannot be clicked.
Wrap your JAVASCRIPT call to my_repeater_show_more in a debounce. This will prevent the function from firing until some minimum amount of time has passed between clicks. Doing so will prevent the function from firing twice if you double click quickly.
More information about writing a debounce in vanilla JS can be found on this excellent blog post.
I'm trying to find a way to display a logged-in user's individual avatar/gravatar (based on their email address) on one of my pages.
So far, I've only been able to find methods to display the page author's avatar, or the same avatar for all users.
I gather that I need to add get_avatar to my functions.php, using something like this:
< a href = "<?php echo get_author_posts_url($post->post_author); ?>"
title = "<?php the_author_meta( 'display_name', $post->post_author ); ?>" >
<? php
if (get_the_author_meta('user_custom_avatar', $post - > post_author) != '') { ?>
< img src = "<?php the_author_meta( 'user_custom_avatar', $post->post_author ); ?>"
alt = "" / >
<? php echo $curauth - > display_name; ?>
<? php
} else {
$current_user = wp_get_current_user();
echo get_avatar($current_user - > user_email, $post - > post_author), '80');
} ?>
< /a>
But I also need to know how to display it in the content of my page/post. Is there something I can use include when editing the page using Wordpress?
Any help would be greatly appreciated!
In any page or post just call it like this
$custom_avatar = get_user_meta($user_id, 'user_custom_avatar', true);
I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,
Data.php
<?php
// connect to the database
require_once 'script/login.php';
//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
. "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = #mysql_query ($query);
if ($result) { //If it ran ok display the records
echo '<div id="feed">';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote>Share</div></div><br />';
};
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection
?>
content.php
<div id="postlist"> FEED GOES HERE.</div>
All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist
It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/
Cheers in advance.
PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck
Hopefully you are allowed to use jQuery.
Add to content.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function getFeed(){
$.post('Data.php',function(data){
$("#postlist").html(data);
});
setTimeout("getFeed();",2000);
}
window.onload = getFeed();
</script>
getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.
This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.
If you use KnockoutJS and jQuery, this might be a good starting point:
http://jquery.com/
http://knockoutjs.com/
content.php
<script type="text/javascript">
$(function() {
// Define our view model that we will feed to KnockoutJS.
var viewModel = {
posts: []
};
// We'll use this variable to keep track of the last post we
// received. When we send our GET request, our php script will be
// able to see $_GET['last_post_date'] and only return the posts
// that come after that.
var last_post_date = null;
// This is the function that will get called every 2 seconds to
// load new data.
var getData = function() {
$.ajax({
url: "/data.php",
data: {
last_post_date: last_post_date
}
}).done( function( data ) {
// We'll assume data.php will give us a JSON object that looks
// like: { posts: [] }
// Append the new posts to the end of our 'posts' array in our
// view model.
viewModel.posts.concat( data.posts );
// Tell KnockoutJS to update the html.
ko.applyBindings( viewModel );
// Store the date of the last post to use in our next ajax call.
last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
});
// In 2 seconds, call this function again.
setTimeout( getData, 2000 );
};
// grab the first set of posts and start looping
getData();
});
</script>
<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
data-bind="template: { name: 'row-template', foreach: posts }"></div>
<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
<a data-bind="attr: {name: PID}"></a>
<div id="postsint">
<a target="_blank" data-bind="
attr: {
href: 'http://www.facebook.com/' + fblink
}
">
<img id="dp" data-bind="
attr: {
title: fbname,
src: 'https://graph.facebook.com/' + fbpic + '/picture'
}
" />
</a>
<div id="posttext">
<!--ko text: post--><!--/ko-->
<blockquote data-bind="text: pd"></blockquote>
<a data-bind="
attr: {
href: 'https://www.facebook.com/dialog/feed?' +
'app_id=505747259483458&' +
'link=http://www.wisp-r.com/share.php?' +
'id=' + PID + '&' +
'picture=http://www.wisp-r.com/images/app-icon.png&' +
'name=Wispr by ' + fbname + '&' +
'caption=' + pd + '&' +
'description=' + post + '&' +
'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
}
">
Share
</a>
</div>
</div>
<br />
</script>
data.php
<?php
// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].
$posts = array();
if ( $result ) {
while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
array_push( $posts, $row );
}
}
echo json_encode( array( 'posts' => $posts ) );
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!
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>