I have created 4 empty galleries(using Nextgen) and I have one list of static image links. The empty galleries have been created so that if someone wants to add images in them later, that gallery will show up in place of the static image links.
The static image links should up if no images are in the Nextgen gallery, but if there are images in the NextGen gallery - use those in place of the static image links.
This is the code I am using for the Nextgen gallery that I'm calling in the page template:
<?php global $nggdb;
$gallery = $nggdb->get_gallery(1, 'sortorder', 'ASC', true, 0, 0);
foreach($gallery as $image) {
echo '<img src="';
echo $image->imageURL;
echo '" />';
}
?>
I know I need to check to see if the specified gallery has images, and then if not, do an else statement, but I'm not exactly sure how to do this.
Any help is greatly appreciated. Thank you.
You could try something like this:
$gallery = $nggdb->get_gallery(1, 'sortorder', 'ASC', true, 0, 0);
if ( !empty($gallery) && is_array($gallery) && count(gallery) > 0 ) {
foreach($gallery as $image) { ... }
} else {
//show static image links
}
Related
Short story:
I'm trying to get the ID of the Header Image in Wordpress.
All I found was this guide, which dosn't seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/
Long Story
I'm trying to make the WP Header responsive with an srcset. so I don't want to use this code
<img id="masthead-bg" src="<?php header_image() ?>" alt="">
...but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.
<img id="masthead-bg"
src="<?php header_image() ?>"
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>"
sizes="100vw" alt="">
Any suggestions?
Try this...
// Get the header image data
$data = get_object_vars(get_theme_mod('header_image_data'));
// Now check to see if there is an id
$attachment_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false;
if($attachment_id) {
// Put your image code here, user whatever function to get image by id you need
}
Note: if you use a proper WordPress function to get the image it should add in all the srcset etc stuff for you, to allow for responsive images.
To answer the original question, I've found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).
function header_img_markup( $html, $header, $attr) {
// we can get the image ID by passing its src url to this method
$header_img_id = attachment_url_to_postid($attr['src']);
// now we can get its metadata from the db
$header_img_data = wp_get_attachment_metadata($header_img_id);
// now we can use the data
$customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];
// ...your custom output here...
return $html;
}
add_filter('get_header_image_tag', 'header_img_markup', 20, 3);
Responsive Wordpress Header Image with fallback:
if (get_header_image() !== '') {
$attachment_id = attachment_url_to_postid(get_header_image());
echo wp_get_attachment_image($attachment_id, 'large');
}
if (get_header_image() == '') {
echo '<h1>'.get_bloginfo( "name" ).'</h1>';
echo '<h2>'.get_bloginfo( "description" ).'</h2>';
}
I have a menu with multiple dropdowns.
I want to show bellow or beside the link of a post or posts in a menu dropdown the featured image. Is it possible?
I've attached an image to this message.
I don't want to know how to style it or something like that.
So let's say I have "Siguranta", I want to display the featured image of that post underneath and a "Read more" link under the image. Many thanks in advance.
Add filter to specific menus
add_filter('wp_nav_menu_args', 'add_filter_to_menus');
function add_filter_to_menus($args) {
// You can test agasint things like $args['menu'], $args['menu_id'] or $args['theme_location']
if( $args['theme_location'] == 'header_menu') {
add_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
}
}
Filter menu
function filter_menu_items($item)
{
if ($item->type == 'taxonomy') {
// For category menu items
$cat_base = get_option('category_base');
if (empty($cat_base)) {
$cat_base = 'category';
}
// Get the path to the category (excluding the home and category base parts of the URL)
$cat_path = str_replace(home_url() . '/' . $cat_base, '', $item->url);
// Get category and image ID
$cat = get_category_by_path($cat_path, true);
$thumb_id = get_term_meta($cat->term_id, '_term_image_id', true); // I'm using the 'Simple Term Meta' plugin to store an attachment ID as the featured image
} else {
// Get post and image ID
$post_id = url_to_postid($item->url);
$thumb_id = get_post_thumbnail_id($post_id);
}
if (!empty($thumb_id)) {
// Make the title just be the featured image.
$item->title = wp_get_attachment_image($thumb_id, 'poster');
}
return $item;
}
And then you want to remove the filter that you applied at the beginning, so that the next menu processed doesn't use the same HTML as defined above in filter_menu_items().
Remove filters
add_filter('wp_nav_menu_items','remove_filter_from_menus', 10, 2);
function remove_filter_from_menus( $nav, $args ) {
remove_filter( 'wp_setup_nav_menu_item', 'filter_menu_items' );
return $nav;
}
So, I will answer my own question. I finally did it with this code:
// get featured image
$thumbnail = get_the_post_thumbnail( $item->object_id );
//display featured image
$item_output .= $thumbnail;
I have to mention that I used this code in the walker class.
I have the following array in my view file (which works):
<?php
$images = array(img("slideshow/demo1.png", "one"),img("slideshow/demo2.png", "two"),img("slideshow/demo4.png", "three"));
$captions = array("first image", "second image", "third image");
foreach (array_combine($images, $captions) as $image => $caption ) {
echo "<li>", $image, "<div class=\"orbit-caption\">",$caption,"</div></li>";
}
?>
However I wish to use the same foreach in a slideshow file across multiple pages with different images displaying so i thought the simplest way would be to create a model page for each page that required different data and having the images and captions in an array as above. I have tried searching how to do this but all the solutions I have found relate to being in a database which is unfortunately not an option.
Also I would like to code it so that if there is not image caption the caption code does not run ie:
"<div class=\"orbit-caption\">",$caption,"</div>
The options I have tried either I get a blank semi transparent box ie it puts down:
<div class="orbit-caption"></div>
Or I getting nothing if I have a caption or not.
I understand a small amount of php but am more of a designer and am fairly new to MVC so will not be offended if anyone has a solution in an idiots guide :) just trying to learn. If anyone has a better solution then please share
Create a helper in application/helpers folder and name it slideshow_helper.php, Now, in slideshow_helper.php write :
<?php
function get_image_array(){
$images = array(img("slideshow/demo1.png", "one"),img("slideshow/demo2.png", "two"),img("slideshow/demo4.png", "three"));
$captions = array("first image", "second image", "third image");
return array_combine($images, $captions);
}
?>
In your controller function from where you load the view for slideshow page, write:
<?php
$data = array();
$this->load->helper('slideshow');
$data['slideshow'] = get_image_array(); #will return the image array from the helper
$this->load->view('view', $data); #load the image array in the view
?>
In your View:
<?php
foreach ($image as $imageSrc => $caption ) {
if($caption != ""){
echo "<li>", $imageSrc, "<div class=\"orbit-caption\">",$caption,"</div></li>";
}
}
?>
I'm creating a Wordpress theme and I'd like to grab the first image in a post as a thumbnail to use in the Facebook's OG meta tag.
I tried using the function get_the_post_thumbnail() but it generates an html img element. Also I'd like to take the first image in the post, without the need of adding a featured image when creating the post.
This should be simple because there are already all thumbnails generated for every post, I'm just not getting it right.
Here I made some function for you that you can hook to add/edit attachment event.
function set_first_as_featured($attachment_ID){
$post_ID = get_post($attachment_ID)->post_parent;
if(!has_post_thumbnail($post_ID)){
set_post_thumbnail($post_ID, $attachment_ID);
}
}
add_action('add_attachment', 'set_first_as_featured');
add_action('edit_attachment', 'set_first_as_featured');
There is a lot of space for improvement, but this one works like a charm too. On every upload / edit attachment, function checks if the post already has featured image. If it has not, image in question is set as featured. Every next picture will be ignored (since post already has featured image).
Maybe someone finds it helpful (you found solution in the middle of my coding, so... :) )
I found this solution:
$size = 'thumbnail'; // whatever size you want
if ( has_post_thumbnail() ) {
the_post_thumbnail( $size );
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
}
I found a solution:
wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail' )[0];
It works fine.
Put this code in your theme's functions.php:
// make the first image of WordPress post as featured image
function first_image_as_featured() {
global $post, $posts;
$first_img_featured = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img_featured = $matches [1] [0];
if(empty($first_img_featured)){ //Defines a default image
$first_img_featured = "/images/default.jpg";
}
return $first_img_featured;
}
Then add the below code inside WordPress loop:
<?php
if (has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<?php }
else { ?>
<img src="<?php echo first_image_as_featured(); ?>" />
<?php
}
?>
If the featured image not set, it will automatically take the first image as featured image.
Source: Get The First Image Of WordPress Post As Featured Image
I have tried the solutions above withou success. So, I build a new and easy solution:
function set_first_as_featured($post_id){
$medias = get_attached_media( 'image', $post_id );
if(!has_post_thumbnail($post_id)) {
foreach ($medias as $media) {
set_post_thumbnail($post_id, $media->ID);
break;
}
}
}
add_action('save_post', 'set_first_as_featured');
When you save a post, this code will check if it has any thumbnail. If not, so it will set the first image attached to this post as thumbnail.
I've a function that will echo the URL of the image from the content of Wordpress.
I got the function work now no problem
// Get Image Attachments
function sa_get_image($postid=0, $size='thumbnail') { //it can be thumbnail or full
if ($postid<1)
$postid = get_the_ID();
$thumb = get_post_meta($postid, "thumb", TRUE); // Declare the custom field for the image
if ($thumb != null or $thumb != '') {
echo $thumb;
}
elseif ($images = get_children(array( //If you upload an image function gets first image
'post_parent' => $postid,
'post_type' => 'attachment',
'numberposts' => '5',
'post_mime_type' => 'image', )))
foreach($images as $image) {
$thumbnail=wp_get_attachment_image_src($image->ID, $size);
?>
<?php echo $thumbnail[0]; ?>
<?php }
else { //If you don't upload or declare as thumb custom field func. gets custom (default) image
echo get_bloginfo ( 'template_directory' ); //same as wp-content/themes/your-theme/
echo '/images/image-pending.gif'; // Put this image into your themes images folder and set the path here
}
}
The only problem now is that the <?php echo $thumbnail[0]; ?> if there are more than one image it will echo all of them something like this
<img src=" http://applesiam.com/wp-content/uploads/2555-05-02_19h14_34-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h14_11-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_43-150x123.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_20-150x150.png http://applesiam.com/wp-content/uploads/2555-05-02_19h13_17-150x150.png ">
As you can see it just separated by some spaces.
Now I just want to have the last image if there is more than one image in the $thumbnail
I'm not really expert with PHP as my semester for PHP course will start next week.
Thanks in advance for any suggestion going to be.
Try:
$imgSrc = end((explode(' ', trim($imgSrc)));
Where $imgSrc is the value you put into <img src="!!!==>>here<<==!!!">.
quickly typed, w/o any warranty. Should leave single URLs intact, and if multiple ones separated by space(s) will take the last.
Try this instead.
echo trim($thumbnail[sizeof($thumbnail)-1]);