Suppose this code prints Youtube:
<?php ytio_empt(); ?>
I want a dynamic way to echo the content of the above function in the place of 'YouTube' in the following xml data:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. 'YouTube' );
I have tried:
$xmlData = file_get_contents( 'http://gdata.youtube.com/feeds/api/users/'. ytio_empt() );
But in vain, the file_get_contents() always fails to open stream.
P.S: Perhaps using HTML will work: to put <?php ytio_empt(); ?> in the place of ytio_empt() in $xmlData. I just don't know how to end PHP function and resume it later..
So as you posted your function in the comments:
function ytio_empt() {
if(empty(get_option('ytio_username'))) {
echo esc_attr( get_option('ytio_id') );
//^^^^
} else {
echo esc_attr( get_option('ytio_username') );
//^^^^
}
}
You will see you don't return the values you just print them! So in order to return them you simply have to change echo -> return.
And if you want to read more about return values see the manual: http://php.net/manual/en/functions.returning-values.php
Related
I'm kind of new to wordpress coding and I've been trying to get a variable from another file.
I have this variable $final_cat_url in /custom/last-category.php that I want to reuse in customtemplate.php.
I've read lots of explanations and the codex, but it's still not working.
I've tried to use the following code in customtemplate.php
get_template_part( 'custom/last-category', null, array('my_final_cat_url'=> $final_cat_url));
echo $args['my_final_cat_url'];
Can you help me with that? Thanks a lot.
Add this function to your functions.php file:
function includeWithVariables($filePath, $variables = array(), $print = true){
$output = NULL;
if(file_exists($filePath)){
// Extract the variables to a local namespace
extract($variables);
// Start output buffering
ob_start();
// Include the template file
include $filePath;
// End buffering and return its contents
$output = ob_get_clean();
}
if ($print) {
print $output;
}
return $output;
}
Instead of using get_template_part(), use this:
<?php includeWithVariables('file_to_include.php', array('final_cat_url' => $final_cat_url)); ?>
In the file you included:
<?php echo $final_cat_url; ?>
I want to insert some HTML tags in a PHP variable, but it results in the PHP variable value only.
It gets the the_subtitle() value and inserts it in the PHP variable and finally adds it to the first part of $content. Why doesn't the HTML tags?
My code:
add_filter( 'the_content', 'add_before' , 20 );
function add_before($content) {
if ( the_subtitle() ){
$custom_content = '<h2 class="subtitlessss">' . the_subtitle() . '</h2><br>';
}
$content = $custom_content . $content;
return $content;
}
You're modifying the output of the_content() by using a filter. Your callback should return a value. However, the function you're using is going to output your subtitle rather than return it.
According to the plugin documentation it works in the same way as WordPress' the_title(). Initially I thought get_the_subtitle() would be more appropriate. However, that isn't the case. Tell the_subtitle() not to output instead (third argument).
function add_before( $content ) {
// Check if the subtitle has been set and assign the value to $subtitle
// Saves us having to call the same function again.
if ( $subtitle = the_subtitle( '<h2 class="subtitlessss">', '</h2><br />', false ) ) {
// Prepend to the content.
$content = $subtitle . $content;
}
// ALWAYS return content.
return $content;
}
add_filter( 'the_content', 'add_before', 20 );
The code you have will always run this line:
$content = $custom_content . $content;
Could that be the issue? Try only modifying $content if the_subtitle() returns a true value, like this:
add_filter( 'the_content', 'add_before', 20 );
function add_before( $content ) {
if ( the_subtitle() ) {
$custom_content = '<h2 class="subtitlessss">' . the_subtitle() . '</h2><br>';
$content = $custom_content . $content;
}
return $content;
}
If you are only seeing the value of $content as your code stands currently, then that means the_subtitle() isn't returning a true value so there is no value in $custom_content. This should throw a Notice: Undefined variable message. Does your wp-config have this line in it?
define('WP_DEBUG', true);
After researching the_subtitle()
OK, so it seems like the_subtitle() takes the same parameters as the native WordPress function the_title as the documentation says here:
Parameters Just like WP's built-in the_title() method,
the_subtitle() tag accepts three parameters:
$before (string) Text to place before the subtitle. Defaults to "".
$after (string) Text to place after the subtitle. Defaults to "".
Therefore, if you want HTML to come before and after the_subtitle, pass it as a parameter:
the_subtitle( '<h2 class="subtitlessss">','</h2><br>' );
To check if the function exists
Also, maybe we should be checking if the_subtitle exists instead of calling it in the if statement? Like so:
if ( function_exists( 'the_subtitle' ) )
The updated code for the entire excerpt would be this:
<?php
add_filter( 'the_content', 'add_before', 20 );
function add_before( $content ) {
if ( function_exists( 'the_subtitle' ) ) {
$custom_content = the_subtitle( '<h2 class="subtitlessss">','</h2><br>' );
$content = $custom_content . $content;
}
return $content;
}
So i am having trouble getting an array from one PHP file to another.
In my first file (file1.php) i got following code:
print_r($order->delivery);
It will get visible when using echo of course, and it outputs the right things. It gives me an array with order information. Now i got another PHP file I need to use this information in.
What i tried so far is including file1.php to file2.php and then echo the array... But the result is empty.
require_once('path/file1.php');
echo print_r($order->delivery);
And i tried echo my array directly in file1.php adding a div like this
echo "<div id='test'>" . print_r($order->delivery, true) . "</div>";
And then getting the inner HTMl of the div with DOM
$dom = new DOMDocument();
$dom->loadHTML("mypageurl");
$xpath = new DOMXPath($dom);
$divContent = $xpath->query('//div[id="test"]');
if($divContent->length > 0) {
$node = $divContent->item(0);
echo "{$node->nodeName} - {$node->nodeValue}";
}
else {
// empty result set
}
Well... none of it works. Any suggestions?
You have to set a variable or something, not echoing it.
file1.php:
$delivery = $order->delivery;
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($delivery['firstname']) ? $delivery['firstname'] : '') . "</div>";
Or you use the $object directly if it is set in file1.php
file2.php
include('path/file1.php');
echo "<div id='test'>" . (isset($order->delivery['firstname']) ? $order->delivery['firstname'] : '') . "</div>";
You can do this by using $_SESSION or $_COOKIE, See here for more detail; PHP Pass variable to next page
Be careful at the variable scope. See this link: http://php.net/manual/en/language.variables.scope.php
And try this code please:
require_once('path/file1.php');
global $order;
print_r($order->delivery);
Defining $order as global should fix your issue.
You could return an array in a file and use it in another like this:
<?php
/* File1.php */
return array(
0,1,2,3
);
-
<?php
/* File2.php */
var_dump(require_once('File1.php'));
I´m drawing an image in PHP from another website, which works. And I´m getting info and from a webpage, which is working. But together it isn´t and only shows the image.
If I cut the picture part and put it at the end it gives an error.
(Use for example nickname Mazey if you need to check out how that JSON page look like)
Has it to do with combining file get contents and my curl function?
<?php
$profPic = json_decode( file_get_contents( 'https://api.kag2d.com/player/'.urlencode( $_GET['nickname'] ).'/avatar/s' ) );
if ( $profPic ) {
if ( isset( $profPic->small ) ) {
$profPic = $profPic->small;
$extension = strtolower( pathinfo( $profPic, PATHINFO_EXTENSION ) );
$content = file_get_contents( $profPic );
if ( $content ) {
header( "Content-type: image/".$extension );
echo $content;
exit();
}
}
} else {
echo "error";
}
$stats = json_decode(file_get_contents('https://api.kag2d.com/player/'.urlencode( $_GET['nickname'] ).'/status' ));
if ( $stats ) {
if ( isset ( $stats->playerInfo ) ) {
echo $stats->playerInfo->username;
} else {
echo 'Error';
}
} else {
echo 'Error';
}
?>
You are attempting to return two different HTTP responses in the same file. If you read the section for images, it does an exit() after printing the image data. This why it stops processing.
When I ran the URLs included in the source, the username returned is the same as the value in the $_GET['nickname']. Do you actually need to look this value up? It would work if you just returned the image.
A solution is to return a JSON document like your third party server is doing, and embed all the information in this. It is legal HTML to have image data as an URL, so the entire thing could be returned as single JSON document. HTML based example from the RFC2397
<IMG SRC="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAA
AMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZt
fzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbt
LiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYG
ejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3i
q9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXy
ym7PHhhx4dbgYKAAA7" ALT="Larry">
Unlike email, noone seems to be developing multi-part mime responses inside HTTP. I did a quick google, but no useful results.
I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {
$urlcall = nav_me_paises(); /* fetches a large html string */
$response = json_encode($urlcall); /* encode to display using jQuery */
//header( "Content-Type: application/json" );
echo $response;
exit;
}
I insert the html on the page, using
function(response) {
jQuery('#navcontainer').html(response);
}
and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
?>
<ul class="navcategorias">
<?php $tquery = $_POST['wasClicked']; ?>
<?php $navligas = get_terms($tquery,'hide_empty=0') ?>
<?php foreach ($navligas as $liga) : ?>
<?php $link = get_term_link($liga); ?>
<li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
$output = '<ul class="navcategorias">';
$tquery = $_POST['wasClicked'];
$navligas = get_terms($tquery,'hide_empty=0')
foreach ($navligas as $liga) {
$link = get_term_link($liga);
$output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
}
$output .='</ul>';
return $output;
}
nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};
var_dump(json_encode(foo()));
string(4) "null"
Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.