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! =)
Related
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.
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');
Can anyone help me create a shortcode such as the one below by using a foreach loop?
The purpose of this shortcode is to generate a playlist, and uses opening and closing tags:
[zoomsounds id="favorites_playlist"] [/zoomsounds]
In between those tags, each song that is to be added to the playlist gets its own shortcode, like this:
[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]
So let's say a user has 2 songs in their playlist, the entire shortcode would look something like this:
[zoomsounds id="favorites_playlist"][zoomsounds_player config="favorites-playlist" source="http://www.test.com/sound/brobob.mp3" type="detect" songname="Song 1" init_player="off" play_target="footer"][zoomsounds_player config="favorites-playlist" source="http://www.test.com/sound/brobob2.mp3" type="detect" songname="Song 2" init_player="off" play_target="footer"][/zoomsounds]
As you can see, each song's shortcode comes one after another, enclosed in the start/close tags.
The easiest way I thought I could do this was to use a foreach loop to generate each song's shortcode. Here is the simple function I wrote.
function streamFavoritesPlaylist() {
$favs[] = get_user_favorites();
echo do_shortcode('[zoomsounds id="favorites_playlist"]');
foreach ($favs[0] as $fav) {
$title = get_the_title($fav);
$post = get_post($fav);
$post_slug = $post->post_name;
$source = '.../mp3/'.$post_slug.'.mp3';
$song_name = get_the_title($fav);
echo do_shortcode('[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]');
}
echo do_shortcode('[/zoomsounds]');
}
And this is the result that I get.
Clearly this is the wrong way to go about doing something like this. Not to mention, the closing tag did not take, and instead has been displayed in text. Perhaps this is why the entire thing is not working?
I should mention that by using the entire shortcode on it's own works fine. It's only when I try to build the shortcode in this manner does it not work.
How would you suggest I go about accomplishing something like this? Thanks a lot.
UPDATE:
Thanks for everyone's input. This is what I came up with, which is similar to what #DACrosby posted, and #TheManiac suggested.
function streamFavoritesPlaylist() {
$favs[] = get_user_favorites();
$shortcode_full = "";
foreach ($favs[0] as $fav) {
$title = get_the_title($fav);
$post = get_post($fav);
$post_slug = $post->post_name;
$source = '.../mp3/'.$post_slug.'.mp3';
$song_name = get_the_title($fav);
$shortcode = '[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]';
$shortcode_full .= $shortcode;
}
return '[zoomsounds id="favorites_playlist"]'.$shortcode_full.'[/zoomsounds]';
}
And where I actually need the shortcode generated, I am using:
<?php echo do_shortcode(streamFavoritesPlaylist()); ?>
It's working perfectly. Thanks again, community.
It's probably not working because [/zoomsounds] isn't a shortcode - it's the closing tag of one. So running the first [zoomsounds ...] and the closing [/zoomsounds] separately doesn't work as expected. Like TheManiac mentioned in a comment, try building the string first then having just one do_shortcode
function streamFavoritesPlaylist() {
$favs[] = get_user_favorites();
$str = '[zoomsounds id="favorites_playlist"]';
foreach ($favs[0] as $fav) {
$title = get_the_title($fav);
$post = get_post($fav);
$post_slug = $post->post_name;
$source = '.../mp3/'.$post_slug.'.mp3';
$song_name = get_the_title($fav);
$str .= '[zoomsounds_player config="favorites-playlist"'
. ' source="'.$source.'" type="detect"'
. ' songname="'.$title.'" init_player="off"'
. ' play_target="footer"]';
}
$str .= '[/zoomsounds]';
echo do_shortcode( $str );
}
Just took your sample code with a simple for loop to print out the result, and it works.
It seems to be some of the string values contains special characters (e.g.: / ' "")
You could check the string values or use some sample code below to test the method.
echo do_shortcode('[zoomsounds id="favorites_playlist"]');
for($i = 0; $i < 5; $i++){
$title = "FAV ".$i;
$post = "FAV ".$i;
$post_slug = "FAV ".$i;
$source = "FAV ".$i;
$song_name = "FAV ".$i;
echo do_shortcode('[zoomsounds_player config="favorites-playlist" source="'.$source.'" type="detect" songname="'.$title.'" init_player="off" play_target="footer"]');
}
echo do_shortcode('[/zoomsounds]');
And the print out:
results
Hope this would help.
I am using a formbuilder plugin in Wordpress which submits the form input to the database as XML data. Now I would like to fetch that data and have it displayed in another page. I have started trying simpleXML to achieve this but now I have hit a road bump.
The XML data that appears in each row of the database follows this format:
<form>
<FormSubject>Report</FormSubject>
<FormRecipient>****#***.com</FormRecipient>
<Name>admin</Name>
<Department>test</Department>
<Value>1000</Value>
<Comments>test</Comments>
<Page>http://***.com</Page>
<Referrer>http://****.com</Referrer>
</form>
I have previously managed to fetch the data that I need using simpleXML from an XML string of the same markup which is in the database but now my question is, how do I do this with a loop for each row in the database?
When the following code is run, wordpress displays a blank page meaning that there is an error:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$string = $statistic->xmldata
$xml = simplexml_load_string($string);
$Name = (string) $xml->Name;
$Department = (string) $xml->Department;
$Value = (string) $xml->Value;
$Comments = (string) $xml->Comments;
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
You are missing ; on line 5
$string = $statistic->xmldata
Should be
$string = $statistic->xmldata;
You should consider enablign WP_DEBUG constant in wp-config.php file. Insert following code to your wp-config.php, just before /* That's all, stop editing! Happy blogging. */
define('WP_DEBUG', true);
/* That's all, stop editing! Happy blogging. */
For more tips on debugging, read the codex
Formbuilder users custom function to extract XML data in formbuilder_xml_db_results Class:
function xmltoarray($xml)
{
$xml = trim($xml);
$match = "#<([a-z0-9_]+)([ \"']*[a-z0-9_ \"']*)>(.*)(</\\1>)#si";
$offset = 0;
if(!preg_match($match, $xml, $regs, false, $offset)) {
return($xml);
}
while(preg_match($match, $xml, $regs, false, $offset))
{
list($data, $element, $attribs, $content, $closing) = $regs;
$offset = strpos($xml, $data) + strlen($data);
$tmp = $this->xmltoarray($content);
$result[$element] = $tmp;
}
return($result);
}
Define that function in your code (before global $wpdb; you don't have to be afraid of same name as that function is defined in Class) and than modify your code in this way:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$xml = xmltoarray( $statistic->xmldata );
$Name = (string) $xml['form']['Name'];
$Department = (string) $xml['form']['Department'];
$Value = (string) $xml['form']['Value'];
$Comments = (string) $xml['form']['Comments'];
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT: edited $xml['Comments'] to $xml['form']['Comments'] and analogous
I fixed it by stripping the backslashes from the XML string using stripslashes()
I'm having a logical problem with my script. The point would be to get a some rows formatted in a table but the header should not be repeated and under all the items should be outputted and than as variable passed to ajax . But I don't see how to solve this.
function abc()
{
global $mainframe;
$db =& JFactory::getDBO();
// Check for request forgeries
if(isset($this->message)){
$this->display('message');
}
// custom: generate token for ajax request
$ajax_token = JHTML::_( 'ajax.token' );
// custom end
// JRequest::checkToken( 'get' ) or jexit( 'Invalid Token' );
$letter_raw = JRequest::getVar('val');
$letter = substr($letter_raw, -1);
$response = '<div class="no-rec">not found</div>';
$html = '';
if (!empty($letter)) {
$query = " SELECT * FROM #__glossary WHERE substr(tterm,1,1) LIKE '$letter%'";
$db->setQuery( $query );
$rows = $db->loadObjectList();
if (count($rows)) {
$header='<table class="stripeMe"><tbody><thead><tr><th>Begriff</th><th>Definition</th></tr></thead><tr>';
foreach($rows as $key => $row) {
$body='<td><span class="title">'.$rows[$key]->tterm.'</span></td><td>'.$rows[$key]->tdefinition.'</td></tr></tbody></table>';
}
$response = $header.$body;
}
$html = $response;
echo $html;
}
}
What exactly is the problem? :)
You probably should not make it a function, since I guess you are just going to load the content in with AJAX?
And you should ADD to the string not override it in each row.
UPDATED, FIXED HTML ERRORS
if (count($rows)) {
// CREATE TABLE AND HEAD
$body = '<table class="stripeMe"><thead><tr><th>Begriff</th><th>Definition</th></tr></thead>';
// TBODY FOR REPEAT INSIDE
$body .= '<tbody>'
foreach($rows as $key => $row) {
$body .= '<tr><td><span class="title">'.$rows[$key]->tterm.'</span></td><td>'.$rows[$key]->tdefinition.'</td></tr>';
}
$body .= '</tbody></table>';
$response = $body;
}
$html = $response;
echo $html;
Well if you are passing the data back as HTML than this will work so your jquery would be:
$('#holderdiv').load('abc.php');
If you are using Something like .post .ajax .get, then you will need to decide what format to pass the data back with so if it's JSON then you will need to format it as such and make sure that your jQuery is told to expect such a response. I can give more help if you can be specific about your situation and what problems you are having.