How to properly call a function from a different file? - php

So I have this code here in my main file.
require_once(plugin_dir_path(__FILE__) . 'load_functions.php');
add_shortcode( 'ccss-show-recipes', 'ccss_show_tag_recipes' );
function ccss_show_tag_recipes() {
global $post;
global $wp;
$html = '';
$url = home_url( $wp->request );
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$currentPage = end($pathFragments);
// $html.= '<p>'.$currentPage.'</p>';
if ($currentPage == 'recipes') {
ccss_load_all_recipes();
} elseif ( in_array( $currentPage ,["cleanse","combine","commence","commit","complete","consolidate"] ) ) {
//load_phases();
} elseif ( in_array( $currentPage ,["basic-marinades","basic-stock-recipes"] ) ) {
// load_recipe_type();
}
return $html;
// Restore original post data.
wp_reset_postdata();
}
and I have function here in load_functions.php
function ccss_load_all_recipes() {
//code here that wont return
$html .= '<p>test</p>'; //--> It wont display this
echo 'test'; //---> This will be displayed
}
The problem when I call ccss_load_all_recipes() it won't return anything, any ideas on what error I made? But when I try an echo statement it returns it
Thanks,
Carl

your function css_load_all_recipes() does not know the variable $html. In order to achieve that you should pass the $html variable into the function and return it again at the end.
// in your main file
$html = ccss_load_all_recipes($html);
// in load_functions.php
function ccss_load_all_recipes($html = '') {
$html .= '<p>test</p>';
return $html;
}
Edit: other possibilities are: declaring $html as a global variable, or passing $html as reference so you don't have to return the altered html back to the main file. But I would advise against both of these options, unless you run into the exact same problem many times within your application.

Related

How to get gravatar in wordpress post using php?

I know the get_avatar() function but its not working. Maybe its due to the complexity of the loops? Please take a look at the code below and let me know! Thanks!
function displaymeta(){
global $post;
$m_meta_description = get_post_meta($post->ID, 'my_meta_box_check',
true);
global $wpdb;
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
foreach($user_nicenames as $nice_name)
{
foreach($nice_name as $name)
{
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
echo"<li>";
echo $name. "<br>";
echo get_avatar($name->ID,50);
echo"</li>";
}
}
}
}
}
add_filter( 'the_content', 'displaymeta' );
I've tried $name,$nice_name, $user_nicenames in function get_avatar($val->ID,50); but nothing seems to work! What am I missing here?
You've already used the right function, which is get_avatar().
But the problem is that the $name as in get_avatar($name->ID,50) is not an object. Instead, it's a string, which could be the user ID or display name (i.e. the user_nicename column in the WordPress users table).
So try replacing the foreach in your displaymeta() function with the one below, where I assigned $name to $nice_name[1], and the user ID is assigned to $user_id:
foreach($user_nicenames as $nice_name)
{
$user_id = $nice_name[0];
$name = $nice_name[1];
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
echo"<li>";
echo $name. "<br>";
echo get_avatar($user_id,50);
echo"</li>";
}
}
}
Additional Note
If you remove the , ARRAY_N as in: (but you don't have to remove it. These are just extra info..)
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
then the variable $nice_name would be an object. Hence you can then access $nice_name->user_nicename like this:
$user_id = $nice_name->id;
$name = $nice_name->user_nicename;
UPDATE
In reply to your comment on the missing content, it's because you didn't capture the variable that WordPress passes through the the_content filter. And you also need to append the LI's to that $content, and finally return the modified content (i.e. $content).
So try this code (which is already utilizing the new foreach code as I provided before or above):
function displaymeta( $content ){
global $post;
$m_meta_description = get_post_meta($post->ID, 'my_meta_box_check',
true);
global $wpdb;
$user_nicenames = $wpdb->get_results("SELECT id,user_nicename FROM
{$wpdb->prefix}users", ARRAY_N);
// Add the opening UL tag. Remove if not needed.
$content .= '<ul>';
foreach($user_nicenames as $nice_name)
{
$user_id = $nice_name[0];
$name = $nice_name[1];
foreach($m_meta_description as $val)
{
$flag=strcmp($name,$val);
if($flag==0)
{
$content .= "<li>";
$content .= $name. "<br>";
$content .= get_avatar($user_id,50);
$content .= "</li>";
}
}
}
// Add the closing UL tag. Remove if not needed.
$content .= '</ul>';
return $content;
}
add_filter( 'the_content', 'displaymeta' );
Hope that helps! =)

How to get all tags from Wordpress page/post as a list in shortcode?

At the end of each page and every post, I would like to output the tags as a list in a shortcode.
Unfortunately, I do not know much about PHP, but someone who can understand will definitely be able to correct my mistake using the code below.
Thank you in advance!
<?php // functions.php | get tags
function addTag( $classes = '' ) {
if( is_page() ) {
$tags = get_the_tags(); // tags
if(!empty($tags))
{
foreach( $tags as $tag ) {
$tagOutput[] = '<li>' . $tag->name . '</li>';
}
}
}
return $tags;
}
add_shortcode('tags', 'addTag');
The method needs to return a string to be able to print any markup.
"Shortcode functions should return the text that is to be used to replace the shortcode." https://codex.wordpress.org/Function_Reference/add_shortcode
function getTagList($classes = '') {
global $post;
$tags = get_the_tags($post->ID);
$tagOutput = [];
if (!empty($tags)) {
array_push($tagOutput, '<ul class="tag-list '.$classes.'">');
foreach($tags as $tag) {
array_push($tagOutput, '<li>'.$tag->name.'</li>');
}
array_push($tagOutput, '</ul>');
}
return implode('', $tagOutput);
}
add_shortcode('tagsList', 'getTagList');
Edit: Removed check for is_page since get_the_tags will simply return empty if there aren't any
Be aware that pages don't have tags unless you've changed something.
That said, this should work. It also adds the <ul> around the tags, but you can change that, and I'm sure you see where. I've used is_singular, but you'll probably get away without that condition at all, unless you do add [tags] in a custom post type and don't want the output there.
I assume you want to add more modification, otherwise webdevdani's suggestion regarding using the_tags is probably simpler.
// get tags
function addTag( $classes = '' ) {
if( is_singular("post") || is_singular("page") ) {
$tags = get_the_tags();
if(is_array($tags) && !empty($tags)) {
$tagOutput = array("<ul>");
foreach( $tags as $tag ) {
$tagOutput[] = '<li>' . $tag->name . '</li>';
}
$tagOutput[] = "</ul>";
return implode("", $tagOutput);
}
}
return "";
}
add_shortcode('tags', 'addTag');

My custom get_the_excerpt() can't get excerpt by ID

On my single.php page I am trying to create a function to give me a custom length excerpt of a specific post by ID.
Below are my two functions I am running.
/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
What I'm using to call the function.
<?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
The issue I am running into is $post is giving me the previous post information however when I pass that into get_the_excerpt it returns the current post excerpt rather than the previous post excerpt.
EDIT
Changed function to this after several people told me I can just pass the $post_id to get_the_excerpt()
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
Still no change.
Adding in setup_postdata($post); fixed my issue.
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
setup_postdata($post);
$output = get_the_excerpt($post);
wp_reset_postdata();
$post = $save_post;
return $output;
}
the following function get two parmeters:
- $num : the number of character you would display
- $post_id: the ID of the post you want to get the content
and:
- if in the content there is the mark, return the text until it
- if $num is = 0 return the content until the first full stop
otherwise return a number of character specified on $num adding "..." at the end of the string
function my_custom_excerpt($num = 0,$post_id=''){
$post=get_post($post_id);
$content=$post->post_content;
if(strpos($content,'<!–more–>')>0){
return substr($content,0,strpos($content,'<!–more–>'));
}else{
if($num===0){
return substr($content,0,strpos($content,'.')+1);
}else{
return substr($content,0,$num).((strlen($content)>$num)?"...":"");
}
}
}

html being processed in string_replace as variable

I have a html <h1 class="title">[VALUE]</h1> where [VALUE] gets replaced with some data when the template is processed.
I would like to used the data that replaces [VALUE] in a php variable.
Something like this,
$my_var = '[VALUE]';
but the above don't work.
function getHTML($articleid, $fieldid, $category = false, $write=false)
{
global $globalreturn;
//$str = fieldattach::getInput($articleid, $fieldid, $category);
$html ='';
$valor = fieldattach::getValue( $articleid, $fieldid , $category );
$title = fieldattach::getName( $articleid, $fieldid , $category );
$published = plgfieldsattachment_input::getPublished( $fieldid );
if(!empty($valor) && $published)
{
$html = plgfieldsattachment_input::getTemplate($fieldid);
if(fieldattach::getShowTitle( $fieldid )) $html = str_replace("[TITLE]", $title, $html);
else
$html = str_replace("[TITLE]", "", $html);
$html = str_replace("[VALUE]", $valor, $html);
$html = str_replace("[FIELD_ID]", $fieldid, $html);
}
//WRITE THE RESULT
if($write)
{
echo $html;
}else{
$globalreturn = $html;
return $html;
}
}
function getTemplate($fieldsids, $file="input", $valor)
{
global $globalreturn;
echo $valor;
$templateDir = dirname(__FILE__).'/tmpl/'.$file.'.tpl.php';
$html = file_get_contents ($templateDir);
$app = JFactory::getApplication();
$templateDir = JPATH_BASE . '/templates/' . $app->getTemplate().'/html/com_fieldsattach/fields/'.$file.'.tpl.php';
if(file_exists($templateDir))
{
$html = file_get_contents ($templateDir);
}
$app = JFactory::getApplication();
$templateDir = JPATH_BASE . '/templates/' . $app->getTemplate().'/html/com_fieldsattach/fields/'.$fieldsids.'_'.$file.'.tpl.php';
if(file_exists($templateDir))
{
include ($templateDir);
}
//return $html;
}
I am trying to use the $valor form function getHTML(); inside the getTemplate();
As you will see in he code above I already tried to call global $globalreturn and then echo $valor; but it doesn't work.
You can try as follows
I think you want pass variable to another page. So add following code in myfile.php
<h1 class="title"><?php define ( 'myVariable', '[VALUE]' ); ?></h1>
And call using require function in your next page.
<?php
require("myfile.php");
?>

Why doesn't my properly defined variable evaluate for length correctly (and subsequently work in the rest of my code)?

I employed the answer Marc B suggested and still got nothing in the variable when I echo'd it after the while loop, so I added a few checks to show status of things as they were processed through the code. When the if/else statement runs next, it shows the result that there is length to the variable. The next if/else statement branches to the else statement and then takes the else statement in the next if/else saying the xpath found nothing. So obviously when I go to use the variable $BEmp3s, it has nothing in it.
This doesn't make much sense to me since in the beginning, the echo of $BEpost_content shows the proper content in its entirety but the evaluation on its length shows nothing/NULL? Please help!
<?php
// Start MP3 URL
$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$xpath = new DOMXpath($doc);
// End MP3 URL
$a = 1;
if (have_posts()) :
while ( have_posts() ) : the_post();
?>
<?php
$BEpost_content = get_the_content();
if (strlen($BEpost_content) > 0) {
echo "<div id='debug_content'>get_the_content has something</div>";
} else {
echo "<div id='debug_content'>BEpost_content is empty</div>" ;
};
$success = $doc->loadHTML($BEpost_content);
if ($success === FALSE) {
echo "<div id='debug_loadcontent'>loadHTML failed to load post content</div>";
} else {
$hrefs = $xpath->query("//a[contains(#href,'mp3')]/#href");
if ($hrefs->length > 0) {
echo "<div id='debug_xpath'>xpath found something</div>";
} else {
echo "<div id='debug_xpath'>xpath found nothing</div>";
};
$BEmp3s = $hrefs->item(0);
};
?>
Here is the function get_the_content() which returns a string to my knowledge:
function get_the_content($more_link_text = null, $stripteaser = 0) {
global $post, $more, $page, $pages, $multipage, $preview;
if ( null === $more_link_text )
$more_link_text = __( '(more...)' );
$output = '';
$hasTeaser = false;
// If post password required and it doesn't match the cookie.
if ( post_password_required($post) ) {
$output = get_the_password_form();
return $output;
}
if ( $page > count($pages) ) // if the requested page doesn't exist
$page = count($pages); // give them the highest numbered page that DOES exist
$content = $pages[$page-1];
if ( preg_match('/<!--more(.*?)?-->/', $content, $matches) ) {
$content = explode($matches[0], $content, 2);
if ( !empty($matches[1]) && !empty($more_link_text) )
$more_link_text = strip_tags(wp_kses_no_null(trim($matches[1])));
$hasTeaser = true;
} else {
$content = array($content);
}
if ( (false !== strpos($post->post_content, '<!--noteaser-->') && ((!$multipage) || ($page==1))) )
$stripteaser = 1;
$teaser = $content[0];
if ( ($more) && ($stripteaser) && ($hasTeaser) )
$teaser = '';
$output .= $teaser;
if ( count($content) > 1 ) {
if ( $more ) {
$output .= '<span id="more-' . $post->ID . '"></span>' . $content[1];
} else {
if ( ! empty($more_link_text) )
$output .= apply_filters( 'the_content_more_link', ' $more_link_text", $more_link_text );
$output = force_balance_tags($output);
}
}
if ( $preview ) // preview fix for javascript bug with foreign languages
$output = preg_replace_callback('/\%u([0-9A-F]{4})/', '_convert_urlencoded_to_entities', $output);
return $output;
}
Your previous question told you to check the length of hrefs to see whether it had content. This is correct because hrefs is an array. It has a length and supports the length property. get_the_content() returns a string (see docs).
To check string length use strlen
To check if null use is_null
To check if set use isset
Difference between isset and is_null
Update
You asked why your code branches incorrectly at the following line:
$hrefs = $xpath->query("//a[contains(#href,'mp3')]/#href");
You also say that $xpath is defined further up in the code. However, you redefine $doc so why would $xpath have the correct values in it?
$success = $doc->loadHTML($BEpost_content); //you change $doc here!
$xpath = new DOMXpath($doc); //so perhaps you should load it into xpath here?
$hrefs = $xpath->query("//a[contains(#href,'mp3')]/#href"); //don't know what this query does. maybe it is broken.

Categories