Wordpress Posts Shortcode - php

I would like to display posts within other posts and pages in WordPress without the use of a plugin. I've searched this site (and others) but haven't found a definitive answer to what I am looking for.
I'd like to display a short-code within posts and pages in this fashion:
[insert_post id="99"]
where 99 is the ID of the post (or page, if possible).
I'd like to pull in the following:
title,
the content (first 30 words),
read more button,
featured image (thumb).
Any tips will be appreciated.

You need to create the shortcode first. This code goes in your functions.php. Here is a basic example to achieve what you are trying to achieve:
function insert_post_shortcode_function( $atts ) {
$attributes = shortcode_atts( array(
'id' => '' // attribute_name => default_value
), $atts );
$return = '';
$post = get_post($attributes['id']);
$return .= get_the_post_thumbnail($post->ID);
$return .= $post->post_title;
$return .= $post->post_content;
$return .= 'Read more';
return $return;
}
add_shortcode( 'insert_post', 'insert_post_shortcode_function' );
Now you can use [insert_post id="x"] in your post's content.
More on creating shortcodes - https://codex.wordpress.org/Shortcode_API

Related

Wordpress | Bulk move content from main editor to custom field

I've used the Advanced Custom Fields plugin to create a new Custom Field in Wordpress. My aim now is to move all Download Links from "the_content", to the newly created Custom Field "the_field('download_link')". The issue is that I have over 10,000 posts to modify. I was wondering if there is a quick way of doing this, rather than manually moving the download link for each post?
Please see the images below for an idea of what I am trying to achieve.
Before | After
One hurdle is that all content is saved in the "wp_posts" table, where the custom field content is saved in the "wp_postmeta" table.
The content saved in the "download_link" custom field, looks like this in the "wp_postmeta" table:
(8214, 2282, 'download_link', '<div class=\"source\"><img src=\"https://www.google.com/image.png\"></div>'),
(8215, 2282, '_download_link', 'field_5cffd35335ce3'),
(8220, 2280, 'download_link', '<div class=\"source\"><img src=\"https://www.google.com/image.png\"></div>'),
(8221, 2280, '_download_link', 'field_5cffd35335ce3'),
(8226, 2278, 'download_link', '<div class=\"source\"><img src=\"https://www.google.com/image.png\"></div>'),
(8227, 2278, '_download_link', 'field_5cffd35335ce3'),
Can this be done at all? Or is the only real way to achieve this is by moving the download links manually?
Thanks in advance for your help.
It can be done automatically if the format of your download link is always the same.
Backup your database
Create a php file named my-cleanup.php.
Loop over all products, grab the link from the description and move it to a post_meta.
Launch the file with WP-CLI:
wp eval-file my-cleanup.php
Sample code
// Select the posts you want
$args = array(
'post_type' => 'post',
'post_status' => 'any',
// -1 means all posts
// For debug, set this to a small number
'posts_per_page' => 3,
);
// Retrieve posts
$query = new WP_Query( $args );
$posts = $query->posts;
// Pattern to match
// [wpdm_package id='90228']
$pattern = "/(\[wpdm_package id='\d+'\])/";
// Process posts one by one
foreach ( $posts as $post ) {
echo "Processing " . $post->post_title . "\n";
$post_args['ID'] = $post->ID;
// Get the shortcode from the post content
preg_match( $pattern, $post->post_content, $matches );
// Do we have a match?
if ( count( $matches) > 0 ) {
// Retrieve shortcode
$shortcode = $matches[0];
// Convert shortcode, maybe add some HTML
$link = do_shortcode( $shortcode );
// remove shortcode from description
$post_args['post_content'] = preg_replace( $pattern, '', $post->post_content );
// Update post
wp_update_post( $post_args );
// Create the post_metas
add_post_meta( $post->ID, '_download_link', 'field_5cffd35335ce3', true );
add_post_meta( $post->ID, 'download_link', $link, true );
}
}
Notes
Backup your database
Test on a few posts to get confidence in your code. You can restore the previous revision in the editor.
Then try on 100, then 1000. You will often find small differences in the way posts are entered.
This might take hours to run on 10.000 posts, which is why you need a WP-CLI command.

Wordpress Shortcode Loop Through Data And Send Current Looped Record To Other Shortcode In Custom Plugin

I am creating a plugin that currently returns a stores inventory from the database.
Right now I am simply outputting the raw text.
What I would like to do is output the data and have other shortcodes render the data.
For example:
[store_inventory]
[/store_inventory]
The above short code would return the following
array([0]=['item_name'='Juice', 'item_number' = '3dsj'], [1]=['item_name'='bread', 'item_number' = 'br3d']);
What I would like to do is have the store_inventory shortcode loop through the array instead of returning the raw array. And pass every individual returned value it loops through to another set of shortcodes so I can write the data into its own html.
My idea would look like this
[store_inventory] //This shortcode loops through the inventory array returned from the database
<div>
<p>[item_name]</p>//This shortcode returns current item_name being looped
<p>[item_number]</p>//This shortcode returns current item_number being looped
</div>
[/store_inventory]
I am just not sure how to handle looping through the array and passing the current data record from the array to the other two shortcodes.
Any help would be appreciated.
I know it would be easy to just spit out the HTML already formatted from the plugin but this would mean no front end editing via wordpress or version control via wordpress.
You have to loop through each item in store_inventory and pass the data in do_shortcode.
I'm not sure how your store_inventory shortcode looks like but see below example:
function story_inventory_loop( $atts ) {
extract( shortcode_atts( array(
//attributes
), $atts ) );
$output = '<div>';
$args = array(
'post_type' => 'post', //your post type
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
$output .= '<p>'.
echo do_shortcode( '[item_name]' . get_the_title() . '[/item_name]' ).
'</p>'.
'<p>'.
echo do_shortcode( '[item_number]' . get_the_excerpt(). '[/item_number]' ).
'</p><!-- ends here -->';
endwhile;
wp_reset_query();
$output .= '</div>';
return $output;
}
add_shortcode('store_inventory', 'story_inventory_loop');
item_name shortcode:
function item_name_shortcode( $atts, $content = null ) {
return $content ;
}
add_shortcode( 'item_name', 'item_name_shortcode' );
item_number shortcode:
function item_number_shortcode( $atts, $content = null ) {
return $content ;
}
add_shortcode( 'item_number', 'item_number_shortcode' );
Hope this helps.

How to show post title that I am creating in the content editor?

Is this possible in Wordpress? I am trying to use a pre-defined template for my contents. To do that, I use something like this:
add_filter( 'default_content', 'custom_editor_content' );
function custom_editor_content( $content ) {
$args = array(
'posts_per_page'=> 15,
'orderby' => array(
'ID' => 'DESC' ,
),
);
$query = new WP_Query( $args );
$query_contents=Array();
while ( $query->have_posts() ) {
$query->the_post();
array_push($query_contents,Array(
"id"=>get_the_ID(),
"title"=>get_the_title(),
"url"=>get_permalink(),
));
}
$content = '
'.get_the_title( $id ).'
';
return $content;
}
But I can't get the post title (the one I am creating at that moment), somehow. Does someone know how to do this? If I put the while statement into $content, it shows the whole query in the editor and that's not what I want of course.
All I want to do is to fetch the post title and show it in the content editor (after posting or before, that wouldn't matter)
Could someone help me out?
I think that at the time of execution of this script (which is before the page loads) the post you are "creating" doesn't exists yet and therefore you cannot fetch its title.
You can try following, as the default_content supports second argument, which is the edited post:
add_filter( 'default_content', 'custom_editor_content' );
function custom_editor_content( $content, $post ) {
...
$content = '
'.$post->post_title.'
';
return $content;
}
However I think you will be facing the same issue as mentioned at the beginning of my answer. If you want to add title to content for new post, you will probably need a javascript which will copy the title into content as you write it (only if the content is still empty).

Create a wordpress Shortcode to display category posts [duplicate]

This question already has an answer here:
Create Wordpress Shortcode to display blog posts
(1 answer)
Closed 7 years ago.
Here is what I have so far. I'm in no way a great programmer. Just a front end guy trying to get this to work. I have a website with different blog categories. For example I have a category called: foods, places, things. I'm trying to write a function where I can execute a shortcode like this:
[list_post mycat="foods"]
Basically I want it to be flexible so whatever category I put inside of "mycat" it will display those blogs.
Again any help would be really appreciated. I know I need to pass a parameter, but I'm honestly unsure how. This is my best effort. Thanks for any hekp
$args = array(
//Pass parameter here
//Something like array (
//$mycat => 'slug';
//);
);
function list_post($mycat){
$query = new WP_Query(array('category_name' => $mycat));
if($query->have_posts()):
while($query->have_posts()):the_post();
the_title();
endwhile;
else:
echo "No posts found!";
endif;
wp_reset_postdata();
}
add_shortcode('list_post', 'list_post')
Your shortcode accepts 1 argument and it's an array with values inside of it. So for this case, $mycat looks like this => array('mycat' => 'foods');, So for this instance, you should use the following to extract and compare:
function list_post($atts){
$arr = shortcode_atts( array(
'mycat' => 'some_default_category',
), $atts );
//now you can call $arr['mycat']; instead of $mycat.
}
Its easier to use get_posts() to achieve this.
function list_post($atts){
$arr = shortcode_atts(
array(
'mycat' => 'slug',
), $atts );
$args = array('category_name' => $arr['mycat']);
$out = '';
$posts = get_posts($args);
if ($posts){
foreach ($posts as $post) {
$out .= $post->post_title . '<br />';
}
}
else {
$out .= 'No posts found!';
}
return $out;
}
add_shortcode('list_post', 'list_post');
Note that it is better to return the output from your shortcode and not echo it.
Edit: Removed usage of extract() function as per #PieterGoosen's advice.

Pulling data for WordPress Jetpack plugin contact form

I have a small form on my website, which I created using Jetpack plugin (it has built-in contact form creator).
I want to pull options for select input from my custom-post-type "artist" (using the titles of the posts). Is there a way to do it?
[contact-field label='Artist' type='select' required='1' options='i want my titles go here separated by commas plus "other" option'/]
The code for the field looks like this. I believe I need to do some php+jquery stuff in this page template, but I can't seem to get it.
With some creativity, yes, it's possible :)
We create another Shortcode to create a "virtual" JetPack shortcode.
I tested this using the default post post_type.
add_shortcode( 'my-jet-form', 'so_14003883_jet_form' );
function so_14003883_jet_form( $atts, $content )
{
// Query our post type, change accordingly
$posts = get_posts( array(
'post_type' => 'post',
'numberposts' => -1,
'post_status' => 'publish'
) );
// Build an array of post titles
$titles = array();
foreach( $posts as $post )
{
$titles[] = $post->post_title;
}
// Convert array into comma sepparated string
$posts_select = implode( ',', $titles );
// Make JetPack shortcode
$return = do_shortcode( '[contact-form][contact-field label="Name" type="name" required="1"/][contact-field label="Artist" type="select" options="' . $posts_select . '"/][/contact-form]' );
return $return;
}
Usage:
adjust the desired post type
adjust the do_shortcode part to suit your original shortcode
put the shortcode [my-jet-form] wherever you want
voilĂ 

Categories