I have flexslider installed on my wordpress and working great, the way it works, it grabs all the images attached to the page and displays them, is it possible to make every image links to its file?
the code I am using is this
<ul class="slides">
<php foreach ( $attachments as $attachment ) { ?>
<li><?php echo wp_get_attachment_image( $attachment->ID, 'cw-post' ); ?>
</li>
<?php } ?>
</ul>
I think this will do the trick.
// Get ID of the attached file
$thumbnail_id = get_post_thumbnail_id(get_the_ID());
// Get attached file. Define what size at the end. DEfault is the thumbnail.
$image_src_arr = wp_get_attachment_image_src($thumbnail_id,'medium');
// Return image source
$image_source = $image_src_arr[0];
I've created this function for myeslf:
/**
* This function will return source url for attached image-
* The get_the_ID is a global WP command that will retrieve current post / page ID
* Using the post ID it will return the attachment ID needed in order to call
* wp_get_Attachment_image_src.
*/
function get_related_image($size){
$image_src_arr = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()),$size);
if(sizeof($image_src_arr) > 0) {
return $image_src_arr[0];
} else {
return false;
}
}
Related
To set a different header per page in WordPress, I usually edit php get_header(); line in theme files such as index.php, page.php...
I wonder if it's possible to change the header file per page with 'get_header' action without editing theme files such as page.php.
I tried the following code, but it didn't work.
function themeslug_header_hook( $name ) {
if(is_front_page() || is_home()) {
$name = 'home';
}
$return $name;
}
add_action( 'get_header', 'themeslug_header_hook' );
Is there any way to set a different header per page within the functions.php file?
Thanks.
I assume you could always do something like this in your functions file.
function get_my_header() {
if( !is_home() ) {
global $post;
// get category by ID
$category = get_the_category($post->ID);
// first category slug
$catslug = $category[0]->slug;
// is there is a category slug call the header-$catslug.php
if (isset($catslug)) {
get_header($catslug);
} else {
// else call normal header.php
get_header();
}// ends !is_home()
// else call normal header
} else {
get_header();
}// ends isset()
} // ends get_myheader function
I've been coding in PHP for a long time, but I'm currently writing my first Wordpress plugin. The plugin's goals are:
Display a form on a public-facing page to collect simple data from
site visitors (first/last name, etc)
Provide a way for admins export the data
I've got a plugin that successfully creates a table on activation and a shortcode that provides a form which successfully stores the submitted data in the database.
On the back-end, I have a dashboard widget that currently displays some stats about the submissions, and my last task is to provide a button to export those stats to CSV, and that's where I'm stumped. I'm not sure how to handle this in WP world...in the past, I would have had the button open a new window to a page that does the exporting and echos a CSV string to the page along with headers that indicate it's a binary file so it's downloaded. In WP, how do I accomplish this? Do I put a PHP script in my plugin directory and have my widget open that page? If so, how does that page gain access to $wpdb to handle the data access?
Here is my code (just for the dashboard widget part) as it stands now:
<?php
/*
Plugin meta details
*/
add_action('init', 'myplugin_buffer_start');
add_action('wp_footer', 'myplugin_buffer_end');
function myplugin_ob_callback($buffer) {
// You can modify buffer here, and then return the updated code
return $buffer;
}
/**
* Action: init
* Runs after WP has finished loading but before any headers are sent, user is already authenticated at this point
* Good for intercepting $_POST/$_GET
*/
function myplugin_buffer_start()
{
ob_start("myplugin_ob_callback");
}
/**
* Action wp_footer
* Triggered near the </body> tag of the user's template by the wp_footer() function.
*/
function myplugin_buffer_end()
{
ob_end_flush();
}
/****************************************************************
* Stats Dashboard Widgets
***************************************************************/
function myplugin_displaytestFormWidget_process()
{
$errors = array();
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
ob_end_clean(); // erase the output buffer and turn off buffering...blow away all the markup/content from the buffer up to this point
global $wpdb;
$tableName = $wpdb->prefix . "myplugin_test_form";
$qry = "select Name, Date from $tableName order by Date desc";
//ob_start(); when I uncomment this, it works!
$result = $wpdb->get_results($qry, ARRAY_A);
if ($wpdb->num_rows)
{
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "myCsvFile-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
//$headrow = $result[0];
//fputcsv($fp, array_keys($headrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
//when I uncomment these lines along with adding ob_start above, it works
//$contLength = ob_get_length();
//header( 'Content-Length: '.$contLength);
}
}
return myplugin_displaytestFormWidget();
}
function myplugin_displaytestFormWidget()
{
global $wpdb;
$tableName = $wpdb->prefix . "myplugin_test_form";
$submissionCount = $wpdb->get_var("select count(Id) from $tableName");
?>
<div><strong>Last entry: </strong>John Q. test (May 5, 2013)</div>
<div><strong>Total submissions: </strong> <?php echo $submissionCount ?></div>
<form id="myplugin_test_export_widget" method="post" action="">
<input type="submit" name="myplugin_export_button" value="Export All" />
</form>
<?php
}
function myplugin_addDashboardWidgets()
{
// widget_id, widget_name, callback, control_callback
wp_add_dashboard_widget(
'test-form-widget',
'test Form Submissions',
'myplugin_displaytestFormWidget_process'
);
}
/****************************************************************
* Hooks
***************************************************************/
//add_action('widgets_init', 'simple_widget_init');
add_action('wp_dashboard_setup', 'myplugin_addDashboardWidgets' );
// This shortcode will inject the form onto a page
add_shortcode('test-form', 'myplugin_displaytestForm_process');
register_activation_hook(__FILE__, 'myplugin_test_form_activate');
You can see in the myplugin_displayTestFormWidget function I'm displaying the form, I just don't know what to do with the button to make it all jive.
Can anyone assist?
At first add following code in your plugin
add_action('init', 'buffer_start');
add_action('wp_footer', 'buffer_end');
function callback($buffer) {
// You can modify buffer here, and then return the updated code
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
Just at the top, right after the plugin meta info like
/**
* #package Word Generator
* #version 1.0
* ...
*/
// here goes the code given above, it'll solve the header sent error problem
And following code will dump a csv file
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
// Somehow, perform the export
ob_clean();
global $wpdb;
$qry = 'your query';
$result = $wpdb->get_results($qry, ARRAY_A);
if ($wpdb->num_rows){
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "myCsvFile-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$headrow = $result[0];
fputcsv($fp, array_keys($headrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
$contLength = ob_get_length();
header( 'Content-Length: '.$contLength);
exit();
}
}
I've implemented similar functionality in another plugin I developed a while ago. I won't claim it's the best practice (I'm not 100% sure if there is such a thing in this instance) but it seemed like a clean and reliable solution for me at the time.
Picking up from where you left off, inside your myplugin_displayTestFormWidget_process function, let me just put some real and pseudo code that should get you rolling.
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
// clear out the buffer
ob_clean();
// get the $wpdb variable into scope so you may use it
global $wpdb;
// define some filename using a timestamp maybe
// $csv_file_name = 'export_' . date('Ymd') . '.csv';
// get the results of your query
$result = $wpdb->get_results("SELECT * FROM your_table");
// loop your results and build your csv file
foreach($result as $row){
// put your csv data into something like $csv_string or whatever
}
header("Content-type: text/x-csv");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=".$csv_file_name);
header("Pragma: no-cache");
header("Expires: 0");
echo $csv_string;
exit;
}
You mentioned you are pretty comfortable with PHP so I didn't really dig into the PHP aspects of getting this done.
Hope that helps, have fun!
(sorry for my English) and I hope to explain!
I'm looking for a solution to display different output for a custom filed, named "cw". The my theme of much use in custom filed, so I created a function to simplify your calls:
/**
* Get custom field of the current page
* $type = string|int
*/
function my_getcustomfield($filedname, $page_current_id = NULL)
{
if($page_current_id==NULL)
$page_current_id = get_page_id();
$value = get_post_meta($page_current_id, $filedname, true);
return $value;
}
said this, I created the custom filed in my theme:
<?php $video_code = my_getcustomfield('cw',get_the_ID()); if(!empty($video_code)) : ?>
<div class="video_code"><?php echo $video_code; ?></div>
Since the custom value is a URL, type: http://127.0.0.1:4001/?f=cadbe2676d5108523f931a68eedb3582, I need to extract just the ID. using this technique PHP Regex to get youtube video ID?, I modified my custom filed in this way:
<?php $video_code = my_getcustomfield('cw',get_the_ID()); $url = $video_code; parse_str(parse_url($url, PHP_URL_QUERY )); if(isset($video_code[0])){ ?>
<div cacaolink="http://127.0.0.1:4001/?f=<?php echo $f; ?>"></div>
<?php } else { ?>
<?php echo 'Video n.d.'; ?></div>
<?php endif; } ?>
In this way everything works perfectly.
Now, the custom value can be those listed below:
<div cacaolink="http://127.0.0.1:4001/megavideo/megavideo.caml?videoid="></div>
<div cacaolink="http://127.0.0.1:4001/videobb/videobb.caml?videoid="></div>
<div cacaolink="http://127.0.0.1:4001/?f="></div>
**Finally here is the problem: How can I use an elseif according to the custom value?
any help is appreciated :)**
So what you need in short is extracting "video id" part from urls having one of 3 structures defined above. If I understood you right, you can just use the next code:
$video_id = preg_replace("/.*\?(videoid|f)=/", '', $customvalue);
Where $customvalue is the value extracted from your custom field with my_getcustomfield.
I'm trying to deal with Wordpress 3.0. It's rather cool thing but I can't get on with one problem. For example, I have such menu tree. Menu tree is constructed from pages.
Home
news
video
audio
Blog
About author
Favourite colors
red
blue
green
My car
wheels
tires
The Idea is:
main menu consists of root elements: home, blog, my car
On the left side I would like to display children elements of current active root element.
For exammple if person is on the "home" page, on the left part he should see:
news
video
audio
If user is on the "Blog" page, he should see:
About author
Favourite colors
red
blue
green
I can't find an API to do that. Can you sugest me please where can I find it?
UPD:
#Jason McCreary
I've seen I've seen wp_list_pages() and tried it. I din't get how can I use it:
Please, see my template for a page:
<?php
/*
Template Name: page_news
* #package WordPress
* #subpackage Twenty_Ten
* #since Twenty Ten 1.0
*/
get_header(); ?>
<h1>page_news</h1>
<h1>Children menu:</h1>
<?php wp_list_pages('echo=0&child_of=8&title_li='); ?>
<div id="container">
<div id="content" role="main">
<?php
/** Get category id by name*/
//$catId = get_category_by_slug('news')->term_id;
query_posts('category_name=news');
get_template_part( 'loop', 'page' );
?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
See this line of code:
<?php wp_list_pages('echo=0&child_of=8&title_li='); ?>
I do have the page with id=8 (I see it in URL). Page with id=8 has several children.
I want to print them, but they are not printed. The output of the function wp_list_pages() is nothing.
I don't know why... :(
You can write a filter_hook to accomplish this.
My method: create an additional start_in argument for wp_nav_menu using my custom hook:
# in functions.php add hook & hook function
add_filter("wp_nav_menu_objects",'my_wp_nav_menu_objects_start_in',10,2);
# filter_hook function to react on start_in argument
function my_wp_nav_menu_objects_start_in( $sorted_menu_items, $args ) {
if(isset($args->start_in)) {
$menu_item_parents = array();
foreach( $sorted_menu_items as $key => $item ) {
// init menu_item_parents
if( $item->object_id == (int)$args->start_in ) $menu_item_parents[] = $item->ID;
if( in_array($item->menu_item_parent, $menu_item_parents) ) {
// part of sub-tree: keep!
$menu_item_parents[] = $item->ID;
} else {
// not part of sub-tree: away with it!
unset($sorted_menu_items[$key]);
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
Next, in your template you just call wp_nav_menu with the additional start_in argument containing the ID of the page you want the children off:
wp_nav_menu( array(
'theme_location' => '<name of your menu>',
'start_in' => $ID_of_page,
'container' => false,
'items_wrap' => '%3$s'
) );
I wrote this to print sub-navs of the pages you may be on. If you want to print out the sub-navigation for each of the pages, get the page parent instead of getting the ID. There would be more involved than that, but it's a start.
$menu = wp_get_nav_menu_items( 'Primary Menu' );
$post_ID = get_the_ID();
echo "<ul id='sub-nav'>";
foreach ($menu as $item) {
if ($post_ID == $item->object_id) { $menu_parent = $item->ID; }
if (isset($menu_parent) && $item->menu_item_parent == $menu_parent) {
echo "<li><a href='" . $item->url . "'>". $item->title . "</a></li>";
}
}
echo "</ul>";`
Check out wp_list_pages(). It is useful for providing child navigation in the sidebar.
mac joost's answer is great, but I would add that if you want the parent item to print, then you shouldn't unset the parent, so line 18 needs to be adjusted accordingly:
if($item->object_id != (int)$args->start_in) { unset($sorted_menu_items[$key]); }
have you seen wp_list_pages?
http://codex.wordpress.org/Function_Reference/wp_list_pages
look closer on child_of attribute
You can use Breadcrumb navxt plugin. It does exactly what you are looking for and its really great.
Breadcrumb NavXT Pugin
I've stopped to explore how to output custom part of worpress site taxonomy on the server-side. I just use jquery to copy active taxonomy branch from main menu and paste it to the page container I need.
I am using this code to have a simple gallery on the page:
<?php echo do_shortcode('[gallery itemtag="ul" icontag="li" size="full" columns="0" link="file" ]'); ?>
The problem now is that the end-user has to upload an image via the Media page before selecting this image as featured image.
I know this could be solved by adding the featured image's ID to the shortcode's exclude list, but how to get this ID automatically?
function exclude_thumbnail_from_gallery($null, $attr)
{
if (!$thumbnail_ID = get_post_thumbnail_id())
return $null; // no point carrying on if no thumbnail ID
// temporarily remove the filter, otherwise endless loop!
remove_filter('post_gallery', 'exclude_thumbnail_from_gallery');
// pop in our excluded thumbnail
if (!isset($attr['exclude']) || empty($attr['exclude']))
$attr['exclude'] = array($thumbnail_ID);
elseif (is_array($attr['exclude']))
$attr['exclude'][] = $thumbnail_ID;
// now manually invoke the shortcode handler
$gallery = gallery_shortcode($attr);
// add the filter back
add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2);
// return output to the calling instance of gallery_shortcode()
return $gallery;
}
add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2);
<?php $id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID ?>
<?php echo do_shortcode('[gallery exclude='.$id.' link="file" itemtag="div" icontag="span" captiontag="p" size="thumbnail" columns="4" ]'); ?>
How about?
echo do_shortcode('[gallery exclude="' . get_post_thumbnail_id( $post->ID ) . '"]');