Integrating Wordpress with Opencart - php

I have an opencart shop and wordpress installation running on the same server and I would like to grab a few articles and show them on the product page in opencart.
Here is the code I inserted on my product page template, however I'm having problems:
<?php
require('blog/wp-blog-header.php');
?>
<?php
$posts = get_posts('numberposts=3&order=ASC&orderby=post_title');
foreach ($posts as $post) : setup_postdata( $post ); ?>
<?php the_date(); echo "<br />"; ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php
endforeach;
?>
I'm gettings this error
Notice: Constant DB_PASSWORD already defined in /home/admin/web/domain.com/public_html/blog/wp-config.php on line 29
ERROR ESTABLISHING A DATABASE CONNECTION
I know DB_PASSWORD is also used by the opencart config, is this the problem? And more importantly is there a solution to this problem?

i think there is a better way to fetch posts from WordPress.
use wp-api to get your posts in json format. then you can process on it as you want.
here is a simple function in php (i have used it as a helper in CodeIgniter.
function blog_posts($site_url = 'http://yoursite.com/', $cat_id = 1, $count = 5, $thumbnails = true)
{
$url = $site_url . 'wp-json/wp/v2/posts?';
$url_data = [
'categories' => $cat_id,
'per_page' => $count,
];
$url_data = http_build_query($url_data, 1, '&');
if ($thumbnails) {
$url_data = $url_data . '&_embed';
}
$final_url = $url . $url_data;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
return $result;
}

An even simpler way could be to use RSS.
Most blogs should produce an RSS feed containing the content you need - this will be quicker and easier to get than an API.
You can then see this answer about how the parse the RSS XML from PHP:
Best way to parse RSS/Atom feeds with PHP

Related

Youtube get video title from id

I understand this may have been answered somewhere, but after looking and looking through numerous questions/answers and other websites, I'm unable to find a suitable answer.
I'm trying to create a page, which will show some video from Youtube. It will show the image, and title. I've managed to do both of these, although i'm having problems with the title. With the code i'm using, it is awfully slow at loading. I assume because of it loading the actual website just to get the title.
This is what i'm using to get the titles currently.
function get_youtube_id($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);
$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;
return $title;
}
So, how would the best way to get a youtube title by the id. The code I have does work, but it also makes the page load very very slow.
Thanks
Here is a simple way to do it using PHP and no library. YouTube already allows you to retrieve video detail information in the JSON format, so all you need is a simple function like this:
function get_youtube_title($ref) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$details = json_decode($json, true); //parse the JSON into an array
return $details['title']; //return the video title
}
The function parameter being the video ID. You could also add a second parameter asking for a specific detail and change the function name so you could retrieve any data from the JSON that you would like.
EDIT:
If you would like to retrieve any piece of information from the returned video details you could use this function:
function get_youtube_details($ref, $detail) {
if (!isset($GLOBALS['youtube_details'][$ref])) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
}
return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}
If you request different details about the same video, the returned JSON data is stored in the $GLOBALS array to prevent necessary calls to file_get_contents.
Also, allow_url_fopen will have to be on in your php.ini for file_get_contents to work, which may be a problem on shared hosts.
You can use Open Graph
Checkout This Link
<?php
require_once('OpenGraph.php');
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$graph = OpenGraph::fetch($url);
// You can get title from array
return $graph->title;
}
It's been 5 years, but my script bellow could be useful.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/watch?v=YOUTUBEID");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$document = htmlspecialchars($output);
curl_close($ch);
$line = explode("\n", $document);
$judul = "";
foreach($line as $strline){
preg_match('/\<title\>(.*?)\<\/title\>/s', $strline, $hasil);
if (!isset($hasil[0]) || $hasil[0] == "") continue;
$title = str_replace(array("<title>", "</title>"), "", $hasil[0]);
}
echo $title;

Function in PHP file doesn't work, when file is called using curl

I've got on my server PHP file, which download something using curl from another server, and save it to db in nested php function. This process is little time-consuming, when I open it in my browser, I must wait ca. 1 minute, but all downloaded records are correct.
Problem is in CRON wget/curl download. When I use
wget http://myserver/myscript.php, or curl http://myserver/myscript.php, connection is closed after 1 byte, and nothing happens on server...
Where make I mistake? Maybe some headers? Why wget/curl don't wait on end of my PHP function like browser? I hope, that require of wp-load.php (I must use for it some Wordpress functions) isn't problem?
Many thanks for responses
Code:
<?php
define('WP_USE_THEMES', false);
require_once("wp-load.php");
$licznik = 0;
// WP_Query arguments
$args = array (
'post_type' => array( 'easy-rooms' ),
'posts_per_page' => 30
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$fields = array(
"funkcja" => "lista_rezerwacji",
"id_pokoju" => get_the_ID()
);
$postvars = '';
foreach($fields as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
rtrim($fields_string, '&');
$url = "http://some.remote.script.to.download.sth.by.curl";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 120);
$response = curl_exec($ch);
curl_close ($ch);
echo $response;
//THIS IS FUNCTION IN SOME WORDPRESS PLUGIN, WHICH DOESN'T WORK WHEN I WGET/CURL THIS SCRIPT
set_reservations($response, get_the_ID());
$licznik++;
}
} else {
// no posts found
}
// Restore original Post Data
print_r($licznik);
wp_reset_postdata();
?>

Function returns post URLs rather than retrieving Facebook Graph API data

require('../wp-blog-header.php');
query_posts('&showposts=-1&order=ASC');
while (have_posts()) : the_post();
$url = the_permalink();
$json = file_get_contents( 'https://graph.facebook.com/fql?q=SELECT%20like_count,%20total_count,%20share_count,%20click_count,%20comment_count%20FROM%20link_stat%20WHERE%20url%20=%20%27' . $url . '%27' );
$json_data = json_decode($json, false);
echo $json_data->data[0]->total_count;
echo '<br>';
endwhile;
The above code, rather than returning the total share count, it returns the posts URLs.
How can I make it return the total_count value for each post ? I suspect line 6 needs to return URLs first before next line does the task..
Regards,
Thanks!
Someone in the WordPress Development network pointed me to this:
the_permalink(); doesn't return the permalink, it prints it, so I should use get_the_permalink(); instead:
$url = get_the_permalink();

Error Using $this when not in object context

First post here so apologies in advance if this is an incorrect format. I am working with the Instagram API to pull images. The Instagram API only returns 1 page of images at a time, but offers pagination and next_url to grab the next page of images. When I use the function fetchInstagramAPI below, to grab only the first page, the php code works fine.
When I attempt to use the loopPages function together with the fetchInstagramAPI function, to try and grab all pages at once, I receive the error "Using $this when not in object context". Any idea? Thank you for the help in advance.
Function fetchInstagramAPI gets our data
<?php
function fetchInstagramAPI($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$contents = curl_exec($ch);
curl_close($ch);
return json_decode($contents);
}
Function loopPages uses pagination and next_url to grab all pages of images
function loopPages($url){
$gotAllResults = false;
$results = array();
while(!$gotAllResults) {
$result = $this->fetchInstagramAPI($url);
$results[] = $result;
if (!property_exists($result->pagination, 'next_url')) {
$gotAllResults = true;
} else {
$url = $result->pagination->next_url;
}
}
return $results;
}
This pulls, parses, then displays the images in a browser
$all_url = 'https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$clientid}';
$media = loopPages($all_url);
foreach ($media->data as $post): ?>
<!-- Renders images. #Options (thumbnail, low_resoulution, standard_resolution) -->
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php endforeach ?>
In PHP and many object oriented languages $this is a reference to the current object (or the calling object). Because your code don't seem to be in any class $this doesn't exists. Check this link for PHP classes and objects.
Since you have just defined your functions in the file you can try calling the function with $result = fetchInstagramAPI($url); (without $this).
edit:
For foreach check if $media->data is in fact an array and try another syntax which i think is easier to read.
edit2:
Since you now know how your $media looks like you can wrap around another foreach loop that will iterate through the pages:
foreach ($media as $page){
foreach ($page->data as $post) {
echo '<!-- Renders images. #Options (thumbnail, low_resoulution, standard_resolution) -->';
echo '<a class="group" rel="group1" href="' . $post->images->standard_resolution->url . '"><img src="' . $post->images->thumbnail->url . '"></a>';
}
}

Change Output of PHP Script to use POST Method

Bear with my inexperience here, but can anyone point me in the right direction for how I can change the PHP script below to output each variable that is parsed from the XML file (title, link, description, etc) as a POST method instead of just to an HTML page?
<?php
$html = "";
$url = "http://api.brightcove.com/services/library?command=search_videos&any=tag:SMGV&output=mrss&media_delivery=http&sort_by=CREATION_DATE:DESC&token= // this is where the API token goes";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 80; $i++){
$title = $xml->channel->item[$i]->video;
$link = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=AQ~~,AAAABvaL8JE~,ufBHq_I6FnyLyOQ_A4z2-khuauywyA6P&bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
#V.Radev Here's another PHP script using cURL that I think will work with the API I'm trying to send data to:
<?PHP
$url = 'http://api.brightcove.com/services/post';
//open connection
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, '$title,$descripton,$url' . stripslashes($_POST['$title,$description,$url']));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// Enable for Charles debugging
//curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:8888');
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>
My question is, how can I pass the variables from my feed parsing script (title, description, URL) to this new script?
I have this code from Brightcove, can I just output the variables from my parser script and send to this PHP script so that the data goes to the API?
<?php
// This code example uses the PHP Media API wrapper
// For the PHP Media API wrapper, visit http://docs.brightcove.com/en/video-cloud/open-source/index.html
// Include the BCMAPI Wrapper
require('bc-mapi.php');
// Instantiate the class, passing it our Brightcove API tokens (read, then write)
$bc = new BCMAPI(
'[[READ_TOKEN]]',
'[[WRITE_TOKEN]]'
);
// Create an array of meta data from our form fields
$metaData = array(
'name' => $_POST['bcVideoName'],
'shortDescription' => $_POST['bcShortDescription']
);
// Move the file out of 'tmp', or rename
rename($_FILES['videoFile']['tmp_name'], '/tmp/' . $_FILES['videoFile']['name']);
$file = '/tmp/' . $_FILES['videoFile']['name'];
// Create a try/catch
try {
// Upload the video and save the video ID
$id = $bc->createMedia('video', $file, $metaData);
echo 'New video id: ';
echo $id;
} catch(Exception $error) {
// Handle our error
echo $error;
die();
}
?>
Post is a request method to access a specific page or resource. With echo you are sending data which means that you are responding. In this page you can only add response headers and access it with a request method such as post, get, put etc.
Edit for API request as mentiond in the comments:
$curl = curl_init('your api url');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $your_data_to_send);
$result_from_api = curl_exec($curl);
curl_close($curl);

Categories