get image from template post in wordpress - php

I use a crowdfunding-plugin for wordpress called personal fundraiser which you can see here. It uses one post-type called cause and another called campaign. The campaign posts uses the cause posts as a template. The reason why i ask here is that the plugin-developer answer questions every second month or so.
There are one shortcode which i want to change the content of. The first thing i want is to get the campaing-image. I probably need a code to get it from the asociated cause (the template). The second thing i want is to echo shortcodes in the $list_content you see below. How do i add shortcodes there? If i use $list_content .= '<?php echo do_shortcode( $content ) ?>' i get php-error. The code i want to change looks like this:
`function pfund_campaign_list() {
global $wp_query;
wp_enqueue_style( 'pfund-user', pfund_determine_file_location('user','css'),
array(), PFUND_VERSION );
$post_query = array(
'post_type' => 'pfund_campaign',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1
);
if ( isset( $wp_query->query_vars['pfund_cause_id'] ) ) {
$post_query['meta_query'] = array(
array(
'key' => '_pfund_cause_id',
'value' => $wp_query->query_vars['pfund_cause_id']
)
);
}
$campaigns = get_posts($post_query);
$list_content = '<ul class="pfund-list">';
foreach ($campaigns as $campaign) {
$list_content .= '<li>';
$list_content .= ' <h2>';
$list_content .= ' '.$campaign->post_title.'</h2>';
$list_content .= '</li>';
}
$list_content .= '</ul>';
return $list_content;
}`
In another function to list the causes, this code is used to get the cause-image, but when i use it in the campaign_list nothing happens:
`$cause_img = get_post_meta($cause->ID, '_pfund_cause_image', true);
if ( $cause_img ) {
$list_content .= '<img class="pfund-image" width="100%" src="'.wp_get_attachment_url( $cause_img ).'"/>';
}`
You can see the whole .php-file here
Any help is very much apreciated.

To get a shortcode in your theme do this
$list_content .= do_shortcode($content);
then you can change in your $list_content, you cant echo in a predefined variable.
In-place of
$list_content .= '<?php echo do_shortcode( $content ) ?>'

Related

My php-wordpress if while loop only runs the first time

My code had a typo!
But im not allowed to delete this so here you have some info on ways you could have done a better job then me ;)
The problem is as follows, My query is skipping a part of my loop.
i have a query that makes a anchor with the title and thumbnail of the post.
it runs the query fine for the first post except for the second post it does not load in the thumbnail, but it does show the title, and the title is only mentioned after the thumbnail, There is no small image that resembles it cant be found either. My first question posted on here so apolagies for misplacing items in the wrong sections.
<?php
// WP_Query arguments
$args = array (
'post_type' => array( 'klantcase' ),
'post_status' => array( 'publish' ),
'nopaging' => true,
'order' => 'ASC',
'orderby' => 'menu_order',
);
// The Query
$klantcases = new WP_Query( $args );
// The Loop
if ( $klantcases->have_posts() ) {
while ( $klantcases->have_posts() ) {
$klantcases->the_post();
echo "<a href=".get_the_permalink().">";
echo get_the_post_thumbnail( null, $size = 'post-thumbnail');?><br><?php
echo the_title();?><br><?php
echo "</a>";
}
} else {
echo "no posts found";
}
// Restore original Post Data
wp_reset_postdata();
Now there is probably many ways to improve this loop but as mentioned im very new to all of this. That said i'd love to hear how you guys would resolve this issue.
Define empty variable on top of while loop.
And in loop concatenate your html with that empty variable.
For Example.
$output = '';
if ( $klantcases->have_posts() ) {
while ( $klantcases->have_posts() ) {
$klantcases->the_post();
$output .= '<a href="'.the_permalink().'">';
$output .= the_post_thumbnail() .'<br>';
$output .= the_title();
$output .= '</a>';
}
} else {
echo "no posts found";
}
echo $output;
You don't need to echo the_title() - it already echoes out, so I'm guessing that's where part of the problem is coming in. You can also make your loop a little more simple.
You don't need the 'post_status' argument, as publish is default.
In your loop, let's use WP's built in echo functions: the_permalink(), the_title() and the_post_thumbnail(). You don't have to pass any arguments to the the_post_thumbnail() because you are just calling the default in your code.
<?php
// WP_Query arguments
$args = [
'post_type' => ['klantcase'],
'nopaging' => TRUE,
'order' => 'ASC',
'orderby' => 'menu_order',
];
// The Query
$klantcases = new WP_Query( $args );
// The Loop
if ( $klantcases->have_posts() ) {
while ( $klantcases->have_posts() ) {
$klantcases->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?><br>
<?php the_title(); ?>
</a>
<?php
}
} else {
echo 'no posts found';
}
// Restore original Post Data
wp_reset_postdata();

counting content with tag in foreach loop wordpress

I am trying to show only tags which have more than specific number of posts. To achieve this I modified my tag-links.php code as below. But with this code I got some weird behavior. My page don't show any tag below the number of content, it is ok, but sometimes it also hides other tags. when I refresh the page it will show different tags or don't show any tags. I am newbie with php syntax, so I am not sure but code seems correct. Can you tell me the code problem, or any practical approach to solve my problem.
PS: code also include this function, every tag redirect user to random post with this specific tag, it works well.
<?php
$tags = get_the_tags( $post->ID );
$separator = ' ';
$output = '';
if ( $tags ) {
$link = "";
$xnumber = 0; //number for contents with specific tag
echo '<div class="entry-tags">';
echo "<p><span>" . __( ) . "</span>";
foreach ( $tags as $tag ) {
$posts = get_posts("post_type=post&orderby=rand");
foreach($posts as $post) {
if(has_tag($tag->term_id)) {
$xnumber++;
if($xnumber >= 1) {
$link = get_permalink($post);
break 1;
} else { }
} else { }
}
if($xnumber >= 1) {
$output .= '<a href="' . esc_url( $link ) . '" title="'
. esc_attr( sprintf( __( "View all posts tagged %s",
'tracks' ), $tag->name ) ) . '">' . esc_html( $tag->name )
. '</a>' . $separator;
unset($link);
unset($xnumber);
} else {
unset($link);
unset($xnumber);
}
}
echo trim( $output, $separator );
echo "</p>";
echo "</div>";
}
Ok, so a couple of things:
1) You arent using the get_posts function the way it's documented. You should be passing in an array of settings. Here's the link to documentation: https://developer.wordpress.org/reference/functions/get_posts/
2) The get_posts() function has a default limit of 5 records. And you're bringing back the list in random order. So, sometimes the 5 records you get will have the tag you're looking for, and sometimes it wont. If you want it to check more records, you'll need to change the numberposts.
Following example displays posts tagged with 'jazz', under 'genre' custom taxonomy, using 'tax_query':
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => 'jazz'
)
)
);
$postslist = get_posts( $args );
That may be more what you're looking for...
A better example using post tags:
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag
)
)
};

How to pull variable output from add_action() with do_action() or is there another method?

May look a very basic thing to the majority here but i'm stuck.
Here is the PHP code that is in my WP functions file (functions.php):
add_action( 'AHEE_event_details_after_the_content', 'my_event_registration_count' );
function my_event_registration_count( $post ) {
$event_obj = $post->EE_Event;
$html = '';
if ( $event_obj instanceof EE_Event ){
$reg_count = EEM_Event::instance()->count_related(
$event_obj,
'Registration',
array(
array(
'STS_ID' => array(
'NOT_IN',
array(
EEM_Registration::status_id_cancelled
)
)
)
)
);
$html .= '<strong>';
$html .= $reg_count;
$html .= ' of ';
$html .= $event_obj->total_available_spaces();
$html .= ' attendees total</strong>';
}
echo $html;
}
I'm trying to get $html output with:
<?php do_action( 'my_event_registration_count', $html ); ?>
Supposed to give me number of registered event attendees. I need to get this number to my WP front page. Nothing.. Also tried with $reg_count. Is this ting supposed to be global? I'm thankful for all the help i can get.
The correct way to write functions with an output in WordPress is with add_filter / apply_filters. It's otherwise the same as add_action / do_action.
Reference:
https://developer.wordpress.org/reference/functions/add_filter/
https://developer.wordpress.org/reference/functions/apply_filters/

Retrieving *number* pages by page id

Hello all,
Resolved
I am currently trying to develop a plugin for wordpress to output three pages into one page, the reason for this is to create something like below.
I have looked around and not seen something similar to what i am wanting to do.
Below is my code & output. EDITED BELOW CODE: as according to Pieter Goosen
<?php
function page_list( $atts ) {
//extracting input parameters (attributes of shortcode)
shortcode_atts( array(
'pages' => ''
), $atts );
/***************************************************Out***********************************************************/
$i = '';
// Get the page id by the page name
$page_names = explode(",", $atts['pages']);
foreach($page_names as $page_name) {
$page = get_page_by_title( ''.$page_name.'', OBJECT, 'page' );
//argument it
$args = array(
'post_type' => 'page',
'posts_per_page' => 3,
'page_id' => ''.$page->ID.''
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$i .= '<div class="page-information">';
$i .= '<div class="page-information-color">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$i .= '<div class="page-information-widget" style="padding-left: 20px;">';
$i .= '<div><img class="alignnone size-medium wp-image-81" src="'.wp_get_attachment_url( get_post_thumbnail_id($the_query->ID,'thumbnail') ).'" alt="" width="auto" height="70" /></div>';
$i .= '<div><h4>'.get_the_title().'</h4></div>';
$i .= '<div> '.wp_trim_words( get_the_excerpt(), 19, '...').' </div>';
$i .= '<div><button class="news-widget-button" type="button">More info ></button></div>';
$i .= '</div>';
}
$i .= '</div>';
$i .= '</div>';
} else {
echo 'No Pages Found! :(';
}
/* Restore original Post Data */
wp_reset_postdata();
}
//returning the output to page
return $i;
}
//instantiate the shortcode
add_shortcode( 'list_pages', 'page_list' );
?>
This continues further down the page another 5/6 times.
I wondering why:
I have multiple entry's
They're not the pages I requested
Could anybody possibly help, fix the probelms?
This line is wrong:
'page__in' => ''.$page->ID.''
page__in does not exists in WP_Query
Whatever ''.$page->ID.'' is, no one knows. This is for you to explain how you got to this
The above line should be
'page_id' => $page_id->ID,
EDIT
Your code is very sloppy and error prone, sorry to say
Never ever use extract(). It has been removed for very specific reasons from core almost two years ago. Please see the Shortcode API on how to properly use attributes without extract()
global $out is really poor coding. Creating globals is evil and should be avoided. Giving your globals easy variable names like $out is even a bigger evil and sin. Just remember, if you use $out outside context, you break your global
Your variable names are confusing, $page vs $Page. You should avoid this. This in a year's time will look like a spelling mistake, and you know what that leads to. This can be really crappy and frustrating to debug due to the similarity in variable names
Resolved
What I done:
Removed the second foreach ( creating twice as many duplicates)
Adjusted the global output ( Changed it to a less guessable output )
Changed the posts_per_page ( As its in a foreach it would get looped, there is no need for three, 1 will do. user can then specify how many pages to display.)
Adjusted the placement of the main container divs classed "page-information && page-information-color"
Please feel free to manipulate below in your own answer for more efficiency or for different adaptions.
<?php
function page_list( $atts ) {
//extracting input parameters (attributes of shortcode)
shortcode_atts( array(
'pages' => ''
), $atts );
/***************************************************Out***********************************************************/
$i = '';
// Get the page id by the page name
$page_names = explode(",", $atts['pages']);
$i .= '<div class="page-information">';
$i .= '<div class="page-information-color">';
foreach($page_names as $page_name) {
$page = get_page_by_title( ''.$page_name.'', OBJECT, 'page' );
//argument it
$args = array(
'post_type' => 'page',
'posts_per_page' => 1,
'page_id' => ''.$page->ID.''
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$i .= '<div class="page-information-widget" style="padding-left: 20px;">';
$i .= '<div><img class="alignnone size-medium wp-image-81" src="'.wp_get_attachment_url( get_post_thumbnail_id($the_query->ID,'thumbnail') ).'" alt="" width="auto" height="70" /></div>';
$i .= '<div><h4>'.get_the_title().'</h4></div>';
$i .= '<div> '.wp_trim_words( get_the_excerpt(), 19, '...').' </div>';
$i .= '<div><button class="news-widget-button" type="button">More info ></button></div>';
$i .= '</div>';
}
} else {
echo 'No Pages Found! :(';
}
/* Restore original Post Data */
wp_reset_postdata();
}
$i .= '</div>';
$i .= '</div>';
//returning the output to page
return $i;
}
//instantiate the shortcode
add_shortcode( 'list_pages', 'page_list' );
?>

How to separate gallery from content in wordpress?

What I want to do
I have a website that uses a CMS I wrote some time ago, and now I am trying to migrate it to wordpress.
At the existing implementation, when someone writes a post, they can add some extra images that are shown as a gallery at the end of the post, as you can see in this page for example (sorry for non english page): http://apollonpatras.gr/news/562/i-bradia-ton-xorigon-parousiasi-xorigikou-programmatos-kai-eisitirion-diarkeias/.
How I think I can do it
I am thinking about letting the users create wordpress galleries and at post save time intercept the post contents and store the gallery image ids in a postmeta field so I can show them however I want.
Also, I will have to strip the galleries from the content before they are shown, since I will show them in my own way later.
What I am trying so far
add_filter('content_save_pre', 'intercept_galleries', 99);
function intercept_galleries($content) {
if (get_post_type() !== 'post') {
return $content;
}
if (has_shortcode($content, 'gallery')) {
// The [gallery] short code exists.
$a = get_post_gallery(0, false);
update_post_meta(get_the_ID(), 'has_gallery', 1);
update_post_meta(get_the_ID(), 'gallery_items', $a['ids']);
} else {
update_post_meta(get_the_ID(), 'has_gallery', 0);
update_post_meta(get_the_ID(), 'gallery_items', "");
}
return $content;
}
add_filter('the_content', 'remove_shortcodes_from_content');
function remove_shortcodes_from_content($content) {
return strip_shortcodes($content);
}
Where it goes wrong
Looks like when the post is originally saved, the postmeta field "has_gallery" is set to 1, but the field "gallery_items" is empty.
When I go to the wordpress editor and just hit update, the fields are absolutely correct.
Also the hook to remove shortcodes from the content is working.
What am I looking for
How can I fix this problem? Also, is there something wrong/stupid with the way I decided to do this? Would some other way be cleaner/easier/faster etc?
Thank you for your time
I've done this a few times and here's how I do it.
First I create a function that will display the gallery in the way that I want. You can modify this according to how you require you gallery markup to be:
function my_gallery_shortcode( $attr ) {
$post = get_post();
if ( ! empty( $attr['ids'] ) ) {
$attr['include'] = $attr['ids'];
}
extract( shortcode_atts( array(
'order' => 'ASC',
'orderby' => 'post__in',
'id' => $post->ID,
'columns' => 3,
'size' => 'large',
'include' => '',
), $attr));
$id = (int) $id;
$columns = (int) $columns;
if ( 'RAND' == $order ) {
$orderby = 'none';
}
if ( ! empty( $include ) ) {
$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if ( empty( $attachments ) ) {
return '';
}
$output = '<div class="slideshow"><ul>';
foreach ( $attachments as $id => $attachment ) {
$thumb = wp_get_attachment_image_src( $id, 'large', false );
$output .= '<li><img src="' . $thumb[0] . '" width="' . $thumb[1] . '" height="' . $thumb[2] . '" alt="' . get_post_meta( $id, '_wp_attachment_image_alt', true ) . '" /></li>';
}
$output .= '</ul></div>';
return $output;
}
You can complicate or simply the function above according to your requirements.
Then in your theme's functions.php add this:
add_shortcode( 'gallery', 'my_gallery_shortcode' );
Now you have two choices:
1) You can allow your user to add a gallery to the main page content by way of them editing the page in question and going to Media > Create Gallery
This will insert the gallery short code which will be formatted according to your function my_gallery_shortcode(), however the gallery can be managed via WordPress's gallery functionality in the admin area and is stored in the database by WordPress in the conventional way.
or
2) You could create a separate WYSIWYG field either through additional code in your functions.php file, or by using a plugin such as Advanced Custom Fields. You would then use this additional WYSIWYG field to allow the user to insert the gallery shortcode in the same way as above. This is virtually the same as option 1 above but you'd have more flexibility as to where you output and position the gallery on the page.
I hope this helps anyone looking to do the same thing.

Categories