Fetching dynamic values from website - php

I am trying to implement dynamic re-marketing for an eCommerce website. I made all the editions in the code to call dynamic values, but still this code doesn't seem to work. I am getting an error "We haven't detected custom parameters for Retail (Google Analytics)" in AdWords.
This is the code-
<script type="text/javascript">
var google_tag_params = {
ecomm_prodid: '<?php echo get_the_title();?>',
ecomm_pagetype: '<?php
if(is_page()){
echo get_the_title()." page";
}else{
session_start();
echo $_SESSION['page_type'];
}
?>',
ecomm_totalvalue: '<?php $product = new WC_Product( get_the_ID() );
session_start();
if($_SESSION['page_type']=="Product details page"){
echo $price = $product->price;
}
session_unset();
session_destroy();
?>',
dynx_itemid: '<?php echo get_the_title();?>',
dynx_pagetype: <?php
if(is_page()){
echo get_the_title()." page";
}else{
session_start();
echo $_SESSION['page_type'];
}
?>,
dynx_totalvalue: <?php $product = new WC_Product( get_the_ID() );
session_start();
if($_SESSION['page_type']=="Product details page"){
echo $price = $product->price;
}
session_unset();
session_destroy();
?>,
};
</script>

It's kinda hard to see what's going on (an example of the HTML output of your PHP script would be helpful), but I noticed that you don't seem to set ecomm_pagetype to one of the allowable values for a retail site, namely one of home, searchresults, category, product, cart, purchase, other.
Also, ecomm_prodid needs to correspond exactly to the product's ID in your Google Merchant feed.

Related

Magento 1.8 - Update Mini Cart After AJAX POST

On a custom page within Magento, I have a simple AJAX Post which passes a product ID to a php script:
jQuery.ajax({
url: 'https://www.mywebsite.com/test/add_to_basket.php',
type: "POST",
data: data,
success: function (data) {
,
error: function (data) {
}
});
Here is the add_to_basket php script:
$i = $_POST['i'];
require_once '../app/Mage.php';
umask(0);
Mage::app();
Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$cart->addProduct($i, 1);
$session->setCartWasUpdated(true);
$cart->save();
This works perfectly, however the mini cart doesn't update. I've read that I need to create a sections.xml file within etc/frontend like so:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="[frontName]/[ActionPath]/[ActionName]">
<section name="cart"/>
</action>
</config>
However I'm not sure what the [frontName]/[ActionPath]/[ActionName] would be in my example. What is the best course of action?
the most important thing – ajax.php :
require_once('/var/www/clients/client0/web1/web/app/Mage.php'); // ABSOLUTH PATH TO MAGE
umask(0);
Mage::app ();
Mage::getSingleton('core/session', array('name'=>'frontend')); // GET THE SESSION
$simbol= Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); // GET THE CURRENCY SIMBOL
$store=Mage::app()->getStore()->getCode(); // GET THE STORE CODE
$cart = Mage::getSingleton('checkout/cart'); //->getItemsCount();
$ajtem=$_POST['item']; // THIS IS THE ITEM ID
$items = $cart->getItems();
foreach ($items as $item) { // LOOP
if($item->getId()==$ajtem){ // IS THIS THE ITEM WE ARE CHANGING? IF IT IS:
$item->setQty($_POST['qty']); // UPDATE ONLY THE QTY, NOTHING ELSE!
$cart->save(); // SAVE
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
echo '<span>';
if($store=='en') echo $simbol;
echo number_format($item->getPriceInclTax() * $_POST['qty'],2);
if($store=='hr') echo ' '.$simbol;
echo '</span>';
break;
}
}
// THE REST IS updatTotalG FUNCTION WHICH IS CALLED AFTER AJAX IS COMPLETED
// (UPDATE THE TOTALS)
echo '<script type="text/javascript">';
echo 'function updateTotalG(){';
echo 'jQuery("#sveUkupno").html(\'';
echo '<strong><span>';
//echo 'JQuery(\'#sveUkupno\').html("<strong><span>';
if($store=='en') echo $simbol;
echo number_format(Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal(),2);
//echo $simbol . ' </span></strong>");';
if($store=='hr') echo ' '.$simbol;
echo " </span></strong>');";
echo '} </script>';
You can see that we detect the currency symbol in the script and the
store that is in use. At the end of the script it generates
updateTotalG script that we use for listing cart quantity value. The
value comes from Magento.

How to set a link based off a post_parent being set - WordPress

I'm learning as I go here and wanted to reach out for a better understanding of how to handle an if statement within WordPress regarding the Parent being set or not.
What I'm trying to do:
I'm attempting to set the URL for an element based off the Parent being set for a page within the "Page Attributes" section. As it currently stands, if a Parent is set for the page, it will update the href value based off the homepage of the parent. However, if no parent is set, it is populating the page URL as the parent.
What I want it to do:
If no parent is set, echo home_url(). This will have it default to the homepage URL if no Parent is set.
Original version:
<?php $permalink = get_permalink($post->post_parent); ?>
Newer version (that needs TLC to work):
PHP:
<?php
if ($post->post_parent) {
$permalink = echo get_permalink($post->post_parent);
} else {
$permalink = home_url();
}
?>
HTML:
Example
Currently, it's not working for the else statement. If I attempt to echo any type of text for the else statement, it appends it to the vainty URL set for the page I'm actively viewing.
What I need the function to do:
<?php
if (a page/post has a parent set within the page attribute) {
$permalink = echo get_permalink($post->post_parent);
} else (if a page/post does not have a parent set within the page attribute) {
$permalink = echo home_url();
}
?>
Any help would be greatly appreciated! Thanks!
on your PHP:
<?php
the_post();
if(count(get_pages('child_of='.$post->ID))!=0){
if($post->post_parent!=0) {
$permalink = get_permalink( end( get_ancestors( get_the_ID(), 'page' )));
} else if ($post->ID==0) {
$permalink = home_url();
} else {
$permalink = get_permalink();
}
} else {
$permalink = home_url();
}
?>
you should remove echo after equals = if you don't want the page to mess up.
then you will be able to get the value you want on your variable $permalink.
P.S. there might be a cleaner way to do this but for now, here it is.
UPDATE: pls check discussion logs to how we arrived with the answer.

Wrong usage of php in a javascript "if"?

I'm trying to automatically switch my background image in wordpress depending on the visitors screen size. If he/she has a big screen, he/she gets the big version of the image. If the screen is small, he/she gets the smaller version. (Just for loading time reduction. The image will be resized to fill the screen afterwards, but that's already working.)
What isn't working is the check wether or not the smaller version even exists. If it doesn't exist, the script should fall back to the bigger version and just use that image. I get a background image, but it's only the big one (wordpress field name "BG_value". The url of the small image is stored in "BG_value-medium").
The images DO exist and the paths passed through the wordpress fields are fine, too, so that is NOT the problem. :/
But, without further ado, I present you the code (from my header.php from wordpress).
<body>
<!-- Wordpress Loop -->
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<script type="text/javascript">
if (($(window).width() < 1340) && (<?php
if(file_exists(bloginfo('template_url').get_post_meta($post->ID, 'BG_value-medium', $single = true))){
echo "true";
}else{
echo "false"; } ?> )){
<?php $bgimg = get_post_meta($post->ID, 'BG_value-medium', $single = true); ?>
} else {
<?php $bgimg = get_post_meta($post->ID, 'BG_value', $single = true); ?>
}
</script>
<div id="bgimage"> <img class="stretch" src="<?php bloginfo('template_url'); ?><?php echo $bgimg; ?>" alt="" /> </div>
<?php endwhile; endif; ?>
I'm sorry if this looks a bit messy, I've been working on this for the last few hours, changing it over and over again.
Any ideas what's going wrong here? Check out the page
You have a big logical error in this. You want to set the bg image with an javascript function, but you never try to set it with javascript, only with an php echo. Take a look at the sourcecode of this javascript snippet in your browser, and you will see what i mean.
You should store the image-pathes in javascript variables inside the then and else, and use them to set the bg image.
Untested:
<script type="text/javascript">
if (($(window).width() < 1340) && (<?php if(file_exists(bloginfo('template_url').get_post_meta($post->ID, 'BG_value-medium', $single = true)))){
echo "true";
}else{
echo "false"; } ?> )){
var bgimage="<?php echo get_post_meta($post->ID, 'BG_value-medium', $single = true); ?>";
} else {
var bgimage="<?php echo get_post_meta($post->ID, 'BG_value', $single = true); ?>";
}
document.getElementById("bgimageimg").src=bgimage;
</script>
<div id="bgimage"><img id="bgimageimg" class="stretch" src="" alt="" /></div>
I've tried to clean up that mess to see what is happening. The following is untested, but if something doesn't work you can now atleast see why it doesn't work.
<?php
if (have_posts()) {
while (have_posts()) {
the_post();
echo '<script type="text/javascript">';
$url = bloginfo('template_url');
$img = get_post_meta($post->ID, 'BG_value-medium', $single = true);
$file_exists = 'false';
if (file_exists($url.$img)) {
$file_exists = 'true';
}
echo 'var bgimg = '.get_post_meta($post->ID, 'BG_value', $single = true).';';
echo 'if ($(window).width() < 1340 && '.$file_exists.') {';
echo ' bgimg = '.get_post_meta($post->ID, 'BG_value-medium', $single = true).';';
echo '}';
echo '$("#bgimage").attr("src", bgimg);';
echo '</script>';
}
}
?>

Echo Twitter share count with PHP?

I am trying to create some text based share buttons for my Wordpress that also output the shared amount. So far I got it working with Facebook and Delicious but I am not sure how to get it going with Twitter.
This is what I did for Delicious.
<?php
$shareUrl = urlencode(get_permalink($post->ID));
$shareTitle = urlencode($post->post_title);
$deliciousStats = json_decode(file_get_contents('http://feeds.delicious.com/v2/json/urlinfo/data?url='.$shareUrl));
?>
<a onclick='window.open("http://delicious.com/save?v=5&noui&jump=close&url=<?php echo $shareUrl; ?>&title=<?php echo $shareTitle; ?>", "facebook", "toolbar=no, width=550, height=550"); return false;' href='http://delicious.com/save?v=5&noui&jump=close&url=<?php echo $shareUrl; ?>&title=<?php echo $shareTitle; ?>' class='delicious'>
<?php
if($deliciousStats[0]->total_posts == 0) {
echo 'Save';
} elseif($deliciousStats[0]->total_posts == 1) {
echo 'One save';
} else {
echo $deliciousStats[0]->total_posts.' saves';
}
?>
</a>
I also got the API Url which calls the tweeted numbers and URL.
http://urls.api.twitter.com/1/urls/count.json?url=SOMESITEURLHERE&callback=twttr.receiveCount
Basically it calls the JSON encoded file, and then gives you the option to share the link in <A></A> tags but instead of showing some text such as Share, it will show the count instead. I'm basically creating some CSS share buttons.
Just use Twitter's own tweet button.
It does that for you and you can style it with .twitter-share-button
(I would post this as a reply but I don't have the privilege.)
Probably you have figured out a solution yourself by now. I just had the same problem and solved it this way:
$handle = fopen('http://urls.api.twitter.com/1/urls/count.json?url=nu.nl', 'rb');
$twitCount = json_decode(stream_get_contents($handle));
fclose($handle);
print_r($twitCount->count);
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
function total($url){
return get_tweets($url); }
Then, use this to get the twitte share count in required place.
<?php echo total("http://website.com/"); ?>

Invite friends to an application - Facebook

Previously my this code worked well but now it do nothing
I want to show an dialog then the user will be able to select some friends and invite them to use this application.
Now this code shows blank page.
<?php
include_once "fbmain.php";
if (isset($_REQUEST['ids'])){
echo "Invitation Sent";
$string = "<script type='text/javascript'>top.location.href='{$fbconfig['appBaseUrl']}';</script>";
echo $string;
}
else {
?>
<fb:serverFbml style="width: 500px;">
<script type="text/fbml">
<fb:fbml>
<fb:request-form
action="<?=$fbconfig['baseUrl']?>/invite.php"
target="_top"
method="POST"
invite="true"
type= <?php echo $fbconfig['appname']; ?>
content="I tried this and love this, what about you ? <fb:req-choice url='<?php echo $fbconfig['appBaseUrl']; ?>' label='Accept' />"
>
<fb:multi-friend-selector
showborder="false"
actiontext=<?php echo $fbconfig['appname' ]; ?>>
</fb:request-form>
</fb:fbml>
</script>
Facebook has deprecated this legacy FBML plugin. While it may still work for a while, you will want to upgrade to their new Requests Dialog, which will be easier to get support for. Also, I've noticed some other deprecated features stop working lately (yet they haven't officially been killed), so this may be the case. But check the javascript console for any errors and post them.
Now to invite friends the only way is to use FB JS
the code
function showInvite()
{
<?php
if (strlen($fbconfig['appname' ])>50)
{
$title = substr($fbconfig['appname' ],0,45);
$title = $title . ' ...';
}
else
$title = $fbconfig['appname' ];
if (strlen($fbconfig['appBaseUrl'])>200)
{
$message = substr($fbconfig['appBaseUrl'],0,200);
$message = 'I just love this App, now it\'s your turn to try it # '.$message;
}
else
$message ='I just love this App, now it"s your turn to try it # '.$fbconfig['appBaseUrl'];
?>
var r = FB.ui({
method : 'apprequests',
message: '<?php echo $message; ?>',
title: '<?php echo $title; ?>',
});
}
Try out code on this page, it would certainly help
https://developers.facebook.com/docs/reference/dialogs/requests/
Seems like this is what you are looking for
<script>
FB.init({
appId : 'APPID',
});
FB.ui({method: 'apprequests', message: 'My Great Request'});
</script>
Have you tried checking the pages source/html? Maybe there are some errors reporting.
You can also in PHP call error_reporting(E_ALL); which will enable all errors to be printed instead of being hidden.
Also, perhaps you could check your browsers JavaScript logs for errors.
In Internet Explorer 9 press F12
In Firefox download firebug.
In Chrome press CTRL + SHIFT + J
function showInvite() {
<?php
if (strlen($fbconfig['appname']) > 50) {
$title = substr($fbconfig['appname'], 0, 45);
$title = $title . ' ...';
} else $title = $fbconfig['appname'];
if (strlen($fbconfig['appBaseUrl']) > 200) {
$message = substr($fbconfig['appBaseUrl'], 0, 200);
$message = 'I just love this App, now it\'s your turn to try it # ' . $message;
} else $message = 'I just love this App, now it"s your turn to try it # ' . $fbconfig['appBaseUrl']; ?>
var r = FB.ui({
method: 'apprequests',
message: '<?php echo $message; ?>',
title: '<?php echo $title; ?>',
});
}

Categories