How to get attribute for shortcode in wordpress? - php

I have constructed a shortcode like this:
[myshortcode id="4"]content[/myshortcode]
with this:
<?php
function f_shortcode($atts, $content = null) {
$returned_string = '<div class="wrap">';
$returned_string .= '<div class="frame">'.$content.'</div>';
$returned_string .= '</div>';
return $returned_string;
}
add_shortcode('myshortcode', 'f_shortcode');
?>
What i need from my shortcode is to retrieve a record from option table in the database (i.e retrieve content based on the id given in the shortcode)
In the options table i have this:
a:1:{i:0;O:8:"stdClass":4:{s:2:"id";s:1:"4";s:9:"title";s:5:"test";s:11:"content";s:5:"test content";s:13:"shortcode";s:29:"[myshortcode id="4"][/myshortcode id="4"]";}}
So to retrieve the content i have added this peace of code to my function:
extract(shortcode_atts(array(
'id' => 'id'
), $atts));
if(get_option('results_options') && get_option('results_options') != ''){
$results = get_option('results_options');
foreach ($results as $result){
if($result->id == '{$id}'){
$content = $result->content;
continue;
}
}
}
In my table the content is there, but it doesnt display or it doesnt even be retrieved, Is there a problem with my code ?
How to get the id="4" parametre inside the function to retrieve the record from the database with it ?

Related

Run custom shortcode twice in the same page

I need help with a wordpress question.
I created a custom shortcode that retrieves a list of data inside a table with specific paramenter:
add_shortcode("archive", "archive_render");
function archive_render($atts) {
extract(shortcode_atts(array(
"rientro" => "no",
"year" => "",
), $atts));
global $wpdb;
$rientro == "si" ? $rientro = "yes" : "no";
$query = "SELECT event_name FROM wp_em_events WHERE EXTRACT(YEAR FROM event_end_date) = ".$year." AND event_end_date < CURDATE()";
$pasts_event = $wpdb->get_col($query);
function get_pasts_event( $pasts_event ){
foreach ( $pasts_event as $past_event_slug ) {
$output .= "<li><a href='".get_site_url()."/eventi/".$past_event_slug."'>$past_event_slug</a></li>";
}
return $output;
}
$string = '[one_third last="'.$rientro.'" class="" id=""][accordian class="" id=""][toggle title="'.$year.'" open="no"]<ul>'.get_pasts_event($pasts_event).'</ul>[/toggle][/accordian][/one_third]';
echo do_shortcode( $string );
}
I want to retrieve all events that has past date compared with the current date.
If I add the shortcode twice in the page, only the first shortcode works and the page stop to display the rest of the content.
Anybody can help me to solve this problem?
wordpress shortcode should return a string, not echoing it
let me re-arrange your code
function get_pasts_event( $pasts_event ){
foreach ( $pasts_event as $past_event_slug ) {
$output .= "<li><a href='".get_site_url()."/eventi/".$past_event_slug."'>$past_event_slug</a></li>";
}
return $output;
}
add_shortcode("archive", "archive_render");
function archive_render($atts) {
extract(shortcode_atts(array(
"rientro" => "no",
"year" => "",
), $atts));
global $wpdb;
$rientro == "si" ? $rientro = "yes" : "no";
$query = "SELECT event_name FROM wp_em_events WHERE EXTRACT(YEAR FROM event_end_date) = ".$year." AND event_end_date < CURDATE()";
$pasts_event = $wpdb->get_col($query);
$string = '[one_third last="'.$rientro.'" class="" id=""][accordian class="" id=""][toggle title="'.$year.'" open="no"]<ul>'.get_pasts_event($pasts_event).'</ul>[/toggle][/accordian][/one_third]';
return $string;
}

Wordpress do_shortcode strange behavior

I am developing a WP plugin which processes shortcodes and displays amazon item data in place of them. The plugin is working as desired, except for a little strange behavior. You can see my test run at http://passivetest.themebandit.com/test-post-for-zon-plugin/ .
If you scroll down on that page, you can see that 4 "1" s are appended to the content. The shortcode is processed 4 times in this page, and each time WP is adding an undesired 1 to the output. I don't understand why this is happening. There is no "1" anywhere in my html files, and its nowhere in the post content. All my functions just return the content that is to be replaced in place of the shortcode. Can someone please give an explanation for it and let me know how to remove these? Thanks in advance..
My code is as follows:
add_shortcode('zon_product', 'zon_process_shortcode');
// Zon Shortcode processor
function zon_process_shortcode($attributes, $content = null) {
global $zon_html_path;
// default options for shortcode
$options = array('asin' => '', 'style' => 'compact', 'loc' => 'com');
extract(shortcode_atts($options, $attributes));
$asin = $attributes['asin'];
// first find asin in local zon_data table
$zdb = ZonDbHandler::instance();
$product = $zdb->findASIN($asin);
if ($product) {
// if product exists in db, render template
return zon_display_product($product, $attributes);
} else {
// product does not exist in database, get data through amazon api worflow
$product = ZonLibrary::getAmazonProduct($asin, $attributes['loc']);
if ($product) {
// product data has been successfully retrieved and saved, render template
return zon_display_product($product, $attributes);
} else {
// error in fetching product data, check amazon access key id and api secret
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'api_error.php');
return $content;
}
}
}
// Renders selected template with product data
function zon_display_product(ZonProduct $product, $attributes) {
global $zon_html_path;
global $zon_path;
// process other shortcode options
$view_vars = array();
$view_vars['style'] = (isset($attributes['style'])) ? $attributes['style'] : "default";
$view_vars['show_price'] = (isset($attributes['show_price']) && $attributes['show_price'] == 0) ? false : true;
$view_vars['price_updates'] = (isset($attributes['price_updates']) && $attributes['price_updates'] == 0) ? false : true;
$view_vars['hide_unavailable'] = (isset($attributes['hide_unavailable']) && $attributes['hide_unavailable'] == 1) ? true : false;
$view_vars['show_desc'] = (isset($attributes['show_desc']) && $attributes['show_desc'] == 0) ? false : true;
// check if template file exists
if (!is_file($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php')) {
$content = 'ERROR! Zon Template not found. Please check you are using a correct value for the "style" parameter.';
return $content;
} else {
// get product array
$product = $product->getArray();
// if product is unavailable and hide_unavailable is true, return unavailable template
if ($view_vars['hide_unavailable']) {
if ((strpos($product['availability'], "Usually") === false) && strpos($product['availability'], "ships") === false) {
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'unavailable.php');
return $content;
}
}
// render chosen template file
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php');
return $content;
}
}

get_post_meta data with shortcode, is that possible

The question is about Wordpress custom meta fields. If my meta field has something in it, I want to display my meta values on my single.php, where I want to. I think it's possible with shortcodes.
function themedemocode($atts,$content = null ) {
return 'What should i do for displaying my meta values ?';
}
add_shortcode('demo', 'themedemocode');
My meta fields ids are ;
ThemeDemoUrl and ThemeDownloadUrl ?
-- SOLVED --
function examplewpkeep($atts, $content = null ) {
global $post;
$custom_content = get_post_custom($post->ID);
if (isset($custom_content["UygulamaDemo"])) {
$meta_content = $custom_content["UygulamaDemo"][0];
}
if (isset($custom_content["UygulamaKaynak"])) {
$meta_content = $custom_content["UygulamaKaynak"][0];
}
$meta_content = '<p style="text-align:center;width:600px;"><a class="informational-link" style="color:#fff;text-decoration:none;margin-right:20px;" href="http://www.fatihtoprak.com/git/'.$custom_content["UygulamaDemo"][0].'" target="_blank" />Önizleme.</a><a class="website-link" style="color:#fff;text-decoration:none;" href="http://www.fatihtoprak.com/git/'.$custom_content["UygulamaKaynak"][0].'" target="_blank" />Dosyaları indir.</a></p>';
return $meta_content;
}
add_shortcode('kaynak', 'examplewpkeep');
Untested, but something like this should work:
function themedemocode($atts, $content = null ) {
global $post;
$meta_content = '';
$custom_content = get_post_custom($post->ID);
if (isset($custom_content["ThemeDemoUrl"])) {
$meta_content .= $custom_content["ThemeDemoUrl"][0];
}
if (isset($custom_content["ThemeDownloadUrl "])) {
$meta_content .= $custom_content["ThemeDownloadUrl"][0];
}
return $meta_content;
}
Of course you can wrap your meta content like the following to apply some html / styling to it
$meta_content .= '<p>' . $custom_content["someKey"][0] . '</p>'.

Incorporating next/ previous in my 'foreach statement

I want to have a previous|next link on my page to change pictures.
I use a function to get relevent elements. However, I do not know what additional code is require in my function and where to place it. Also what should be in the html section.
I have looked at many pages on next/previous from 'foreach' but I cannot seem to relate to them.
Code:
function image_data($image_album_id) {
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
$query = mysql_query("SELECT $fields FROM `album_images`
WHERE `image_album_id`=$image_album_id AND `member_id`= '1'");
$ query_result = mysql_fetch_assoc($query);
foreach ($args as $field) {
$args[$field] = $query_result[$field];
}
return $args;
}
Html Page:
Last|
Next
</div>
<?php
$image_album_id =$_GET['image_album_id'];
$image_data = image_data($image_album_id, 'album_id', 'albumname', 'ext', 'timestamp');
echo '';
?>
<td class="smallfont albumthumb2" align="center" valign="middle" >
<img alt="" class="album_cover" src="<?php echo 'images/albums/thumbs/'. $image_data['album_id']. '/'. $image_album_id. '.' .$image_data['ext'];?> " height="175px" width="175px">
</td>
Many thanks. I hope I make sense.
Thanks for the speedy response.
Since there is a lot to look at and digest I thought I would just see if it works.
Alas no.
There is a parse error: syntax error, unexpected
'<' on line
$prev_link = Previous;
The only thing I notice within that section was an extra curly bracket after 'title="$prev_name"}'
I see there is the same for the 'title="$next_name"}'
WIth reference to your specific questions.
I get to the album_viewT page when I click on a link in a previous page. This contains tiny thumbnails. The link being localhost/Testing/album_view.php?artist_id=4&image_album_id=4 as an example.
Not sure if I fully understand "order of date is by image_album_data
Yes there are almost 3,000 rows in the database.
I should also mention that album_id has been replaced by artist_id.
Should the href be changed to "album_view.php/id/...
Your question lacks some data i.e. what is the page you are visiting that produces this code (the URL that is) and how is your data sorted. For instance I can see that you are providing potentially more information using the album_viewT.php? script but that is not necessarily the one that displays the HTML that you have produced.
So after all this I will make some assumptions and hopefully that will give you the right guidance to get to the solution.
I am assuming that your visiting page is http://mysite.com/albums/id/25
I am also assuming that the order of the data is by image_album_id.
Finally I am assuming that you have data in your db and I don't need to check whether there are returned data in the template for the current image. You will need to sort that out yourself.
You will need to get the data first from the database:
function image_data($image_album_id)
{
$results = array(
'previous' => FALSE,
'current' => FALSE,
'next' => FALSE,
);
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
// Current record
$results['current'] = get_data(
$fields,
"AND image_album_id = {$image_album_id}"
);
// Previous - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['previous'] = get_data(
$fields,
"AND image_album_id < {$image_album_id} " .
"LIMIT 1"
);
}
// Next - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['next'] = get_data(
$fields,
"AND image_album_id > {$image_album_id} " .
"LIMIT 1"
);
}
// If all went well the $results array will contain the data
// for the 3 records. If we are at the beginning or the end,
// the previous and/or next will be FALSE
return $results;
}
function get_data($fields, $where = '')
{
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE member_id = 1 %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
}
For your HTML page:
<?php
$image_album_id = $_GET['image_album_id'];
$image_data = image_data(
$image_album_id,
'album_id', 'albumname', 'ext', 'timestamp'
);
$prev_link = '';
$next_link = '';
if ($image_data['previous'])
{
$prev_id = $image_data['previous']['album_id'];
$prev_name = $image_data['previous']['albumname'];
$prev_link = <a href="/albums/id/{$prev_id}" title="$prev_name"}>Previous</a>";
}
if ($image_data['next'])
{
$next_id = $image_data['next']['album_id'];
$next_name = $image_data['next']['albumname'];
$next_link = <a href="/albums/id/{$next_id}" title="$next_name"}>Next</a>";
}
$curr_id = $image_data['current']['album_id'];
$curr_ext = $image_data['current']['ext'];
?>
<?php echo $prev_link; ?>|<?php echo $next_link; ?>
</div>
<td class="smallfont albumthumb2" align="center" valign="middle">
<a href="album_viewT.php?images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}; ?>
<img alt="" class="album_cover"
src="images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}"; ?>
height="175px"
width="175px" />
</a>
</td>
Note: I have split the line for the img and a tags in the HTML file for clarity.

Block/Theme not 'return'ing $output

This is the issue.
I have a block called 'User Favorites Block'
It's placed in the region 'First Sidebar'
'First Sidebar' appears on the front-page.
The function is supposed to grab the data from the f25_favorites table and list them inside the block. Right now the table is an empty array.
When I return $output, none of my divs or anything are output.
When I do print($output), everything is displayed.
This is my test code to show that my 'if' statement is returning true. http://d.pr/zDph
/*
* f25_favorites_my_favorites theme
*/
function theme_f25_favorites_my_favorites($mypaths) {
dsm($mypaths);
print_r(count($mypaths));
$output .= 'n<div id="f25-favorites">n';
$output .= '<div id="f25-favorites-list">n';
if (count($mypaths) == 0) {
$output .= "No favorites have been added";
print "No favorites have been added";
}
else {
foreach ($mypaths as $indpath) {
$output .= l($indpath->title, $indpath->path, $attributes = array());
}
}
$output .= '</div>n';
$output .= '<div id="f25-favorites-add">n';
$output .= '</div>n';
$output .= 'n</div>n';
return $output;
}
This outputs this: http://d.pr/Uhrs
Note the 0 on the top left, that's the output of the 'count()'
And the print of the text within the 'if'
So, this is my theme:
/*
* f25_favorites_my_favorites theme
*/
function theme_f25_favorites_my_favorites($mypaths) {
/*dsm($mypaths);
print_r(count($mypaths));*/
$output .= '\n<div id="f25-favorites">\n';
$output .= '<div id="f25-favorites-list">\n';
if (count($mypaths) == 0) {
$output .= "No favorites have been added";
}
else {
foreach ($mypaths as $indpath) {
$output .= l($indpath->title, $indpath->path, $attributes = array());
}
}
$output .= '</div>\n';
$output .= '<div id="f25-favorites-add">\n';
$output .= '</div>\n';
$output .= '\n</div>\n';
return $output;
}
It's called with this hook_theme() function:
/*
* Implentation of hook_theme().
*/
function f25_favorites_theme () {
return array(
'f25_favorites_my_favorites' => array (
'arguments' => array ('mypaths' => array())
),
);
}
Which is called with this hook_block() function:
/*
* Implementation of hook_block().
*
*/
function f25_favorites_block($op = 'list', $delta = 0, $edit = array()) {
if ($op == 'list') {
$blocks = array();
$blocks['f25-favorites'] = array(
'info' => t('User Favorites Block'),
'cache' => BLOCK_NO_CACHE,
);
return $blocks;
}
if ($op == 'view') {
switch ($delta) {
case 0:
$mypaths = f25_favorites_user_favorites();
$block = array(
'subject' => t('User Favorites Block'),
'content' => theme_f25_favorites_my_favorites($mypaths)
);
return $block;
};
}
}
Noteworthy
My theme is a 'Sub-theme' of a theme called 'Zen'
Zen has a block.tpl.php which looks like this: http://d.pr/AaO1
Here is the full code of my module: http://d.pr/cGqc
It could be a region-related problem. Try switching to Garland and add the block to a plain old Garland region, and see if it appears.
If you see it in Garland then make sure your sub-theme really is defining that "First Sidebar" region and then actually printing its variable in the tpl files.
(FWIW I tried your code on Garland and it displays the block fine.)
Also, you might want to change your function call from:
theme_f25_favorites_my_favorites($mypaths)
to:
theme('f25_favorites_my_favorites', $mypaths)
...if you want to keep the code flexible (i.e. have Drupal call any preprocess functions and allow other people, or yourself in the future, to override the template's output)

Categories