wordpress shortcode render content in dashboard also - php

I am using a simple wordpress shortcode
function my_recent_post()
{
echo 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );
with the shortcode [recent] and its working fine and visible in front page,
but the problem is, its printing the hello in the dashboard also.
below is the screenshot, can anyone please help.
Update:
I was actually trying to show posts, so can you help me with this, because it renders the lists of posts in the dashboard itself like the "hello". I tried:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ( $postslist as $post ) :
setup_postdata( $post ); ?>
<div>
<?php the_date(); ?> <br /> <?php the_title(); ?> <?php the_excerpt(); ?>
</div>
<?php endforeach;
wp_reset_postdata();
return;
}
add_shortcode('lorem', 'lorem_function');

Based on your comments to me & Nikita Dudarev, what you need to do is create a variable to hold all the post information and then return it. Using the function you posted as an example:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
// create a variable to hold the post information
$html ="";
foreach ( $postslist as $post ) :
setup_postdata( $post );
$backgroundstyle = "";
// get the featured image and set it as the background
if ( has_post_thumbnail() ) { // make sure the post has a featured image
$imageurl = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' ); // you can change "medium" to "thumbnail or full depending on the size you need
// add the css for the background image. You can include background-size etc ad required
$backgroundstyle = "background-image: url('".$imageurl[0]."');";
}
// add the information to the variable
$html .= '<div style="'.$backgroundstyle.'">';
$html .= get_the_date();
$html .= "<br />";
$html .= get_the_title();
$html .= get_the_excerpt();
$html .= "</div>";
endforeach;
wp_reset_postdata();
return $html;
}
add_shortcode('lorem', 'lorem_function');
Note that the_date(), the_title() and the_excerpt() all display the information (just like echo).
Instead you must use get_the_date(), get_the_title() and get_the_excerpt() - these get the same information, but instead of displaying it directly, they return it as a variable which you can then store in your html string to be returned.
Update:
As you don't want to use the variable name on each line for whatever reason, you can do it like this:
$html .= "<div>".get_the_date()."<br />".get_the_title().get_the_excerpt()."</div>";
I'm not sure why you specifically want to change it to do that - it makes absolutely no difference to how it works, it just makes it harder to read and identify any errors :-)

Your function must return a value, not output
function my_recent_post()
{
return 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );

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();

Custom wordpress function to display related posts based on multiple tags

I'm building a wordpress site and want to show related posts based on tags when viewing a single post. Currently I'm using the below function to do this and it works.
My issue is that I want to prioritise related posts that have the most tags in common. Usually I have 3-5 tags for each posts so I want to display posts with 3 tags in common before 1 tag for example. I've tried some different code snippets that should be able to do this but I haven't managed to get it to work so far.
Any help will be appreciated, thanks.
function smak_related_posts() {
global $post;
$tags = wp_get_post_tags( $post->ID );
if($tags) {
foreach( $tags as $tag ) {
$tag_arr .= $tag->slug . ',';
}
$args = array(
'tag' => $tag_arr,
'numberposts' => 4,
'post__not_in' => array($post->ID),
'post_type' => array('post', 'projects'),
);
$related_posts = get_posts( $args );
if($related_posts) {
echo '<footer class="entry-footer">';
echo '<h3>Se også...</h3>';
echo '<div id="masonry-loop">';
get_template_part( 'template-parts/content', 'masonry_sizer' );
foreach ( $related_posts as $post ) : setup_postdata( $post );
get_template_part( 'template-parts/content', 'masonry' );
endforeach; }
}
echo '</div>';
echo '</div>';
wp_reset_postdata();
}

Exclude excerpt from wordpress wp_query

Hellow everyone!
I am showing blog of posts in additional wp template and everything works fine, but I've made some kind of gallery from it, and I don't need to show anything except gallery and title.
Inside posts I have this:
[gallery ids="1618,...,1634"]
<h2>...</h2>
<p>...</p>
text without format, etc.
As you can see, I am using a gallery shortcode. I need it to be shown, but all other content to be excluded from the loop.
Really appreciate your help in this question...
My template code:
<?php
/*
* Template name: Блог
*/
$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 9,
'paged' => $current_page,
'cat' => 8
);
query_posts( $args );
$wp_query->is_archive = true;
$wp_query->is_home = false;
while(have_posts()): the_post();
?>
<div class="foto_posts">
<?php the_content() ?>
<?php echo '' . get_the_title() . '';?>
</div>
<?php
endwhile;
if(function_exists('page_navi_slider')) page_navi_slider();
try to replace <?php the_content() ?> to <?php the_title() ?>
if you just want to show gallery shortcode try this
replace
<?php the_content() ?>
to
$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'gallery') {
$shortcode = $matches[0];
echo do_shortcode($shortcode);
}
Try this for getting galleries and videos use the get_post_meta_key()
<?php get_post_meta($post_id,'key_name',1);?>
If it returns an array then traverse that array to get the images link and video links
add_shortcode('gallery', 'gallery_shortcode_fancybox');
function gallery_shortcode_fancybox($attr) {
$attachment_ids = explode(',',$attr['ids']);
$args = array(
'post__in' => $attachment_ids,
//'cat' => 8 if category needs to be shown pass it in shortcode , same as ids
);
$gallery_posts = query_posts( $args );
foreach ($gallery_posts as $key => $value) {
//do the stuff here
echo '<h2>'. $value->post_title;'</h2>';
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($value->ID);
echo '<p><img src="'.$feat_image.'" ></p>';
}
}

Display WordPress post content images and text separately

I'm looking at the WordPress blog and I'm trying to figure out how to display the image and text separately when displaying the content. The reason I want to do this is because I want to create a custom layout, and I need to be able to move the image around without grabbing all the text at the same time. Does anyone have any idea on how to do this?
Example of what i've already got: (UPDATED)
<?php
require('blog/wp-blog-header.php');
?>
<?php
$args = array( 'numberposts' => 2, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
$postslist = get_posts( $args );
echo '<ul id="latest_posts">';
foreach
($postslist as $post) : setup_postdata($post);
echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' );
$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );
?>
<li>
<strong>
<?php the_date(); ?>
</strong>
<br />
<?php the_title(); ?>
<p>
<?php echo $image[0]; ?>
</p>
</li>
<?php endforeach; ?>
</ul>
ERROR:
Warning: DOMDocument::saveHTML() expects exactly 0 parameters, 1 given
in
/hsphere/local/home/poulaum/isosec.co.uk/blog/wp-includes/functions.php
on line 4874
and image to show what the above code displays:
You can make use of featured images. This featured image will not be included in post content. However, if you already have your images included in post content, then you need to strip the post content down in two parts, as you've said in your question.
I have two functions, one that returns all the images (or any html tag content) from the content and one function that returns the text without the desired tag/images. Both of these functions uses DOMDocument
The first function get_content_without_tag() returns the content which has been stripped from images. There are two parameters
$html -> The text with images to be stripped, in this case, use apply_filters( 'the_content', get_the_content() ) to use the post content
$tag -> The name of the tag to strip out, in this case, 'a' as a tags hold images
Here is the function
function get_content_without_tag( $html, $tag )
{
// Return false if no html or tag is passed
if ( !$html || !$tag )
return false;
$dom = new DOMDocument;
$dom->loadHTML( $html );
$dom_x_path = new DOMXPath( $dom );
while ($node = $dom_x_path->query( '//' . $tag )->item(0)) {
$node->parentNode->removeChild( $node );
}
return $dom->saveHTML();
}
You would then use this in place of the_content() where you would need to display text only, stripping out the complete <a/> tag in which the images are as follows
echo get_content_without_tag( apply_filters( 'the_content', get_the_content() ), 'a' )
The second function, get_tag_without_text() returns the content between the desired tag, in your case, images. The parameters are exactly the same as the first function. Here is the function
function get_tag_without_text( $html, $tag )
{
// Return false if no html or tag is passed
if ( !$html || !$tag )
return false;
$document = new DOMDocument();
$document->loadHTML( $html );
$tags = [];
$elements = $document->getElementsByTagName( $tag );
if ( $elements ) {
foreach ( $elements as $element ) {
$tags[] = $document->saveHtml($element);
}
}
return $tags;
}
This function returns an array of images should you use a tags, so, to display the first image, use the function as follow:
$image = get_tag_without_text( apply_filters( 'the_content', get_the_content() ), 'a' );
echo $image[0];
EDIT
The code above is was only tested with WP_Query and not with get_posts. I have fixed a few bugs in the code above and also in your code to make it work with get_posts
Here is a working example of your code. (Just remember to update the the functions with the new ones above)
<?php
$args = array(
'numberposts' => 2,
'post_status' => 'publish',
'post_type' => 'post',
'orderby' => 'date'
);
$postslist = get_posts( $args );
echo '<ul id="latest_posts">';
foreach ( $postslist as $post ) {
setup_postdata($post);
$content = get_content_without_tag( $post->post_content, 'a' );
$image = get_tag_without_text( $post->post_content, 'a' );
if ( $content )
echo apply_filters( 'the_content', $content );
?>
<li>
<strong>
<?php the_date(); ?>
</strong>
<br />
<a href="<?php the_permalink(); ?>" title="<?php the_title();?>">
<?php the_title(); ?>
</a>
<?php
if ( $image ) {
?>
<p>
<?php echo apply_filters( 'the_content', $image[0] ); ?>
</p>
<?php
}
?>
</li>
<?php
}
echo '</ul>';

Wordpress Custom fields display file URL

I have the following code and need to show THREE things from my custom post type called fact-sheet.
The Title
The summary (fact_sheet_summary)
A file upload URL (fact_sheet_pdf_link)
I can get the first two to work but no idea how to do the third.
Basically my output should be...
The Title
The Summary paragraph
Click here to download as PDF
Any ideas how I can query to list all of these post type results? Is there a better way to do this rather than what I have below? The main problem is, I can't get the URL of the uploaded file.
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
));
if($posts)
{
foreach($posts as $post)
{
echo '<span class="fact-sheet-title">' . get_the_title($post->ID) . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . the_field('fact_sheet_summary') . '</span></p>';
}
}
?>
I think It's better to use query_posts() as you can use The Loop default structure.
As for the custom fields (Using ACF Plugin), you're using the_field(), which automatically echoes the retrieved field value. You can use, in other hand, the get_field() function, which just returns the value of the field.
You could do something like this:
// Query all posts from 'fact-sheet' post_type
query_posts(array(
'numberposts' => -1,
'post_type' => 'fact-sheet',
'order' => 'ASC',
// Getting all posts, limitless
'posts_per_page' => -1,
));
// Loop throught them
while(have_posts()){
the_post();
echo '<span class="fact-sheet-title">' . get_the_title() . '</span><br />';
echo '<p><span class="fact-sheet-summary">' . get_field('fact_sheet_summary') . '</span></p>';
// Echos the link to PDF Download
echo '<p>Click here to download as PDF</p>';
}
// Once you're done, you reset the Default WP Query
wp_reset_query();
In case you might need further explanation about wp_reset_query(), check this out.
Can you try this? It's slightly modified from the manual of the WP Codex (not much)
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$args = array(
'post_type' => 'attachment',
'post_mime_type' => array('application/pdf'),
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
the_attachment_link( $attachment->ID, true );
echo '<p>';
echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
}
endwhile; endif; ?>
</ul>
If it works, maybe it's better to modify a working sample to your needs - by adding your custom fields. Just my thoughts :-)

Categories