I want to display the Facebook comment count on my blog archives.
My wordpress site has the following php function in function.php
// Get combined FB and WordPress comment count
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
$wpCount = get_comments_number();
$realCount = $count + $wpCount;
if ($realCount == 0 || !isset($realCount)) {
$realCount = 0;
}
return $realCount;
}
This is how I am using the function on a template file inside a loop <?php echo full_comment_count(); ?>
Most of the time most of the articles show "0" comments. But sometime one or 2 of them work. what am i doing wrong
Try this
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
if ($count == 0 || !isset($count)) {
$count = 0;
}
echo $count;
}
Related
I've been working on a movie review website and I can't quite get the calculate average rating functionality working. In the code below, In the first instance I am grabbing the current rating of the movie [$totalRating] via an API and setting the counter [$numRatings]. Then via an API I am collecting all of the ratings of that movie, attempting to to add them to the total rating, updating the counter within the loop.
However, when I rate movies they simply are updated to the registered rating (say I input an 8 it becomes an 8) and the division never takes place. Was wondering if anyone has any solutions or can see where I am going wrong?
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 1;
$totalRating = $baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (isset($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
$numRatings++;
$totalRating = $totalRating + $row['rating'];
}
}
$avgUserRating = $totalRating / $numRatings;
return $avgUserRating;
}
Might just need a small adjustment
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 0; //1
$totalRating = 0; //$baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (array_key_exists($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
++$numRatings;
$totalRating += $row['rating'];
}
}
return $numRatings > 0 ? $totalRating / $numRatings : $baseRating;
}
Bit of an interesting question that's puzzling me, so I know how to count how many times a shortcode is called on a page using a static counter. However, I want to reset the counter whenever the parent shortcode is called:
<?php function gw_row($atts, $content = null) {
return '<div class="gw-row">'.do_shortcode($content).'</div>';
} add_shortcode("gw-row", "gw_row");
function gw_column($atts, $content = null) {
static $count = 0; $count++; if($count > 5){$count = 0}
return '<div class="column">'.do_shortcode( $content ).'</div>';
} add_shortcode("gw-column", "gw_column");?>
So explaining it further, there will be multiple [gw-row] shortcodes on a page, this is the 'Parent Shortcode'. Within this shortcode I use [gw-column]. I want to count how many columns are used on the page within each parent shortcode.
Example:
[gw-row]
[gw-column]$Count = 1[/gw-column]
[gw-column]$Count = 2[/gw-column]
[/gw-row]
Reset $count
[gw-row]
[gw-column]$Count = 1[/gw-column]
[gw-column]$Count = 2[/gw-column]
[gw-column]$Count = 3[/gw-column]
[/gw-row]
Reset $count
I've thought about making [gw-row] an object and resetting $count just after the closing of the <div> which might work, but I wonder if there's a better way?
My thoughts:
<?php function gw_row($atts, $content = null) {
global $count;
ob_start();?>
<div class="gw-row">
<?php do_shortcode($content);?>
</div><?php $count = 0;?>
<?php return ob_clean();
} add_shortcode("gw-row", "gw_row");
function gw_column($atts, $content = null) {
$count++; if($count > 5){$count = 0}
return '<div class="column">'.do_shortcode( $content ).'</div>';
} add_shortcode("gw-column", "gw_column");?>
Ok so I was seriously overthinking this, the solution is quite simple and close to what I suggested.
Simply define $count globally and set it to 0 in the [gw-row] shortcode. This will reset it every time it's called:
<?php function gw_row($atts, $content = null) {
global $count; $count = 0;
return '<div class="gw-row">'.do_shortcode($content).'</div>';
} add_shortcode("gw-row", "gw_row");
function gw_column($atts, $content = null) {
global $count; $count++; if($count > 5){$count = 0}
return '<div class="column">'.do_shortcode( $content ).'</div>';
} add_shortcode("gw-column", "gw_column");?>
Please apologyze my English.
I'm developing a kind of sitemap.xml system for my website to include products to my database from external websites, like Google did with his "Spiders", I just developed this whole script to verify if an specific sitemap.xml contains every required tags, and It works: If any tag is missing, the script returns an error, but if all "products" has the required tags, the script returns a success message.
But I only have one problem: if the xml external file has any error like a missing "close" tags, the script stop working and returns an error.
I need to verify the if the external xml file contais any error, and then proceed with the rest of the code that I wrote, if the result is "NO".
this is my developed script:
<?
$sitemap = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['sitemap'])))));
$ref = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['ver_id'])))));
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
include dirname(dirname(__FILE__))."/connectdb.php";
$query = "SELECT * FROM website WHERE `ver_id` = '$ref'";
$result = $mysqli->query($query);
/* array asociativo */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$url = $row['url'];
$long_url = $url.'/'.$sitemap;
?>
<?php
$total = 0;
$xml=simplexml_load_file("$long_url") or die("Error: Cannot create object");
$count = $xml->count();
foreach($xml->children() as $producto) {
$id = $producto->id;
$titulo = $producto->titulo;
$descripcion = $producto->descripcion;
$fotografia = $producto->fotografia;
$precio = $producto->precio;
$costo = $producto->costo;
$horario = $producto->horario;
$tiempo = $producto->tiempo;
$cobertura = $producto->cobertura;
$keywords = $producto->keywords;
$destacar = $producto->destacar;
$delivery = $producto->delivery;
if (!empty($id) && !empty($titulo) && !empty($descripcion) && !empty($fotografia) && !empty($precio) && !empty($costo) && !empty($horario) && !empty($tiempo) && !empty($cobertura) && !empty($keywords) && !empty($destacar) && !empty($delivery)) {
$total = $total + 1; } else { $total = $total - 1; }
}
if($total < $count){ header("Location:/user/sitio.php?id=$ref&mensaje=1"); } else
if($total == $count){
$query = "UPDATE website SET sitemap='$sitemap',sitemap_status='active' WHERE ver_id='$ref'";
$result = $mysqli->query($query);
header("Location:/user/sitio.php?id=$ref&mensaje=2");
}
?>
Solved with this simple script!
<?
$dom = new DOMDocument;
$dom->Load($long_url);
if ($dom->validate()) {
echo "Valid File";
} else { echo "Invalid File"; }
?>
thanks to everyone.
Good day!
I have archive page, that displays all posts tags in sidebar.
In Archive page i have loop:
global $b;
$i=1;
$b=0;
while( have_posts() ){
the_post();
global $arch_postID;
global $b;
if($i == $num_fetch && $sidebar == 'both-sidebar' ) {
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb30">';
$arch_postID[] = get_the_ID();
echo $i;
}elseif($i == $num_fetch) {
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb20">';
$arch_postID[] = get_the_ID();
echo $i;
}else{
echo '<div class="blog-item' . $item_index . ' gdl-divider ' . $item_class . ' mb50">';
$arch_postID[] = get_the_ID();
echo $i;
}
$b++;
$i++;
In function.php for sidebar i have:
global $arch_postID;
global $b;
global $archive_uri;
if ( !empty($arch_postID) && is_archive() ){
echo '<style>.archive-hide-side{display:none;}</style>';
for($i = 0; $i <= $b-1; $i++){
$array_keys = array_keys($arch_postID);
$terms_array = wp_get_post_terms($arch_postID[$i],'vip'); // Get terms for post_id in array( $arch_postID[0], $arch_postID[1] ... )
$terms_array_next = wp_get_post_terms($arch_postID[$i+1],'vip'); // Get terms for post_id in array( $arch_postID[1], $arch_postID[2] ... )
$terms_array_last = wp_get_post_terms($arch_postID[$b-1],'vip'); // Get terms for $arch_postID[$i = last]
$terms_array_first = wp_get_post_terms($arch_postID[0],'vip'); // Get terms for first post ID
for($a = 0; $a <= count($a)+1; $a++){
$name_array = $terms_array[$a]->name;
$name_array_next = $terms_array_next[$a]->name;
$name_array_last = $terms_array_last[$a]->name;
$name_array_first= $terms_array_first[$a]->name;
if( $name_array == $name_array_next or $name_array_next == $name_array_last or $name_array_last == $name_array_first ){ // check if next term->name is similar to previous of last, or first
$name_array_next = NULL; // assigned NULL to value of term->name
$name_array_last = NULL; // assigned NULL to value of term->name
$name_array_first = NULL; // assigned NULL to value of term->name
echo '<div style="color:black">'. $arch_postID[$i] .' || '. $name_array .'</div>'; // Display term->name values without next or previous term->name
}
}
}
}
This code works like - prntscr.com/7rrozc - displays all tags( on right side ) and post ID(on left side ) divided by "||" from current archive page posts.
End result:
I need to display only one tag, if it similar to another.
I have two posts, their tags: first post( "vip 1", "vip 2", "vip 3", "OTHER" ), second post( "vip 1", "vip 2", "OTHER 2").
In sidebar must be displayed "vip 1", "vip 2","vip 3","OTHER","OTHER 2".
I'm stuck on that question for two days, i have no solution in my mind... If someone knows how to do that, pls help me out. I would be happy for a little hint.
P.S. Thanks for you help and time!
I find solution, works great!
$Path=$_SERVER['REQUEST_URI'];
$Prev_path=$_SERVER['HTTP_REFERER'];
$URI='http://gradrich.tmweb.ru'.$Path;
global $arch_postID;
global $b;
global $archive_uri;
global $brr;
if ( !empty($arch_postID) && is_archive() ){
for($i = 0; $i <= $b-1; $i++){
$terms_array = wp_get_post_terms($arch_postID[$i],'super_vip');
for($a = 0; $a <= 100; $a++){//goes a 100 time from 0, to show all parameters from wp_get_post_terms array
$terms_name[] = $terms_array[$a]->name;// create array of terms->name
$terms_slug[] = $terms_array[$a]->slug;// create array of terms->slug
}
}
$result_name = array_unique($terms_name);// check name array for unique variables
$result_slug = array_unique($terms_slug);// check slug array for unique variables
for($f = 0, $s = 0; $f <= count($terms_name), $s <= count($terms_slug); $f++, $s++){// do loop for all unique variables
if(!empty($result_name[$f]) && !is_category() || !empty($result_slug[$s]) && !is_category()){//check if variables not empty than get proper name and slug from two arrays
echo '<div class="tagCloud-cover" id="cat-hide">' . $result_name[$f] . '<a href="'. $Prev_path .'" >-</a></div>';
} else{
}
}
}
I'm running a social network and right now my search.php shows results for people, and tags. How can I add an RSS Feed? I own a blog and I wanted to add my RSS Feed to the search so whenever someone searches for a topic it will show up on the search page.
Here's the search.php code:
$feed = new feed();
$feed->db = $db;
$feed->url = $CONF['url'];
if(isset($_SESSION['username']) && isset($_SESSION['password']) || isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$feed->user = $verify;
$feed->username = $verify['username'];
$feed->id = $verify['idu'];
if(isset($_GET['tag'])) {
$skin = new skin('shared/top'); $top = '';
$TMPL['theme_url'] = $CONF['theme_url'];
$TMPL['private_message'] = $verify['privacy'];
$TMPL['avatar'] = $verify['image'];
$TMPL['url'] = $CONF['url'];
$top = $skin->make();
}
}
}
$feed->per_page = $settings['perpage'];
$feed->time = $settings['time'];
$feed->censor = $settings['censor'];
$feed->smiles = $settings['smiles'];
$feed->c_per_page = $settings['cperpage'];
$feed->c_start = 0;
$feed->l_per_post = $settings['lperpost'];
$TMPL_old = $TMPL; $TMPL = array();
$skin = new skin('shared/rows'); $rows = '';
if(empty($_GET['filter'])) {
$_GET['filter'] = '';
}
// Allowed types
if(isset($_GET['tag'])) {
// If the $_GET keyword is empty [hashtag]
if($_GET['tag'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$hashtags = $feed->getHashtags(0, $settings['qperpage'], $_GET['tag'], null);
$TMPL['messages'] = $hashtags[0];
} else {
// If the $_GET keyword is empty [user]
if($_GET['q'] == '') {
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['messages'] = $feed->getSearch(0, $settings['qperpage'], $_GET['q'], $_GET['filter']);
}
$rows = $skin->make();
$skin = new skin('search/sidebar'); $sidebar = '';
if(isset($_GET['tag'])) {
$TMPL['trending'] = $feed->sidebarTrending($_GET['tag'], 10);
} else {
$TMPL['genre'] = $feed->sidebarGender($_GET['filter'], $_GET['q']);
}
$TMPL['ad'] = generateAd($settings['ad6']);
$sidebar = $skin->make();
$TMPL = $TMPL_old; unset($TMPL_old);
$TMPL['top'] = $top;
$TMPL['rows'] = $rows;
$TMPL['sidebar'] = $sidebar;
if(isset($_GET['logout']) == 1) {
$loggedIn->logOut();
header("Location: ".$CONF['url']."/index.php?a=welcome");
}
$TMPL['url'] = $CONF['url'];
if(isset($_GET['tag'])) {
$TMPL['title'] = '#'.$_GET['tag'].' - '.$settings['title'];
} else {
$TMPL['title'] = $LNG['title_search'].' - '.$_GET['q'].' - '.$settings['title'];
}
$skin = new skin('shared/timeline_x');
return $skin->make();
Please help :)
Try this example
<?php
$articles = $pages->find('blog')->children()->visible()->flip()->limit(10);
snippet('feed', array(
'link' => url('blog'),
'items' => $articles,
'descriptionField' => 'text',
'descriptionLength' => 300
));
?>
link:
This is the main link in our feed, which takes the visitor back to our site. In this case we want them to get back to our blog, so we build an url to our blog with the url() helper function.
items:
As items for our feed, we pass the set of $articles we found in the first line. The feed snippet will automatically take care of getting the right info out of those $articles (like title, url, etc.)
descriptionField:
If you want to show a description for each item in your feed, you need to specify a field, which is available in any item and should be used for the description.
descriptionLength:
This is maximum number of characters the description will have. An excerpt is automatically generated by the feed snippet.