How do I create a shortcode? - wordpress

How to fix this shortcode?
function post_id_shortcode_func () {
Global $post;
return full_real id = "' $post-> ID '";
}
add_shortcode (' post_id_shortcode ', ' post_id_shortcode_func ');
Is this in a shortcode without $post-> ID
<? php
do_shortcode (' [full_real id = "' $post-> ID '"] ');
?>
It's basically a shortcode to a shortcode without the php function.
result [full_real id = "current post id"]
is a spreadsheet with the change of several currencies

Try this code,
// Creating short code
function full_real_func( $atts ){
$a = shortcode_atts( array(
'id' => '', //Provide any default id.
), $atts );
return esc_attr($a['id']); //returns id.
}
add_shortcode( 'full_real', 'full_real_func' );
//Calling
echo do_shortcode( '[full_real id="' .$post->ID .'"]' );
Hope this will help you!

function ShowProduct()
{
$data = "Welcome to wordpress shortcode.";
return $data;
}
add_shortcode('products', 'ShowProduct');
For more examples- Codex Wordpress

Related

is_feed() not working for Custom Post Types

I have a CPT called quotes with ACFs that I want to add to my RSS feed.
My rss url is example.com/feed/?post_type=quotes
When I use is_feed() this code works. But it doesn't work when I try to limit it to only the quotes CPT using: is_feed('quotes')
function add_fields_to_rss ($content) {
if(is_feed('quotes')) {
$post_id = get_the_ID();
$output = '<div><p>' . get_field('the_quote', $post_id) . '</p>';
$output .= '<h3 style="text-align: right;">' . get_field('quoted', $post_id) . '</h3>';
$output .= '</div>';
$content = $content.$output;
}
return $content;
}
add_filter('the_content','add_fields_to_rss');
Is there anything else I need to do so that this function will work with my quotes CPT only?
if I understand currently you want to add all custom posts types to the rss feed?
If so the following should work:
add_filter( 'request', 'myfeed_request' );
function myfeed_request( $qv ) {
if ( isset( $qv['feed'] ) ) {
// gett all custom posts types
$qv['post_type'] = get_post_types();
}
return $qv;
}
Tell me if this is what you're looking for
EDIT 1: Aswering your updated question and comment
The following is for adding specific customs posts types to the rss feed
<?php add_filter( 'request', 'multiple_CPT_to_rss' );
function multiple_CPT_to_rss( $qv ) {
if ( isset( $qv['feed'] ) && !isset( $qv['post_type'] ) ) {
$qv['post_type'] = array( 'post', 'my_CPT_1', 'my_CPT_2' );
}
return $qv;
}; ?>
CPT creates default rss links in the form of My rss url is example.com/feed/?post_type=my_post_type
If seems that doesn't work with is_feed('my_post_type')
I'm guessing to make it work you need to create the feed with add_feed()
But I didn't test that because I went another way.

How to ensure shortcode result doesn't break formatting?

I want to add a shortcode which will execute a DB query and return the result.
Here's my functions.php:
function get_posts_count($cat){
global $wpdb;
$a = shortcode_atts( array(
'id' => ''
), $cat );
$id=$a['id'];
$count=$wpdb->get_results( "SELECT `count` FROM `wpmy_term_taxonomy` WHERE `term_id`=$id");
foreach($count as $row)
echo '('.$row->count.')';
}
add_shortcode( 'postCount', 'get_posts_count' );
This is the shortcode in the editor:
And here's the end result:
The value in this case 1 appears above the text Real Estate. How can I make sure it is displayed within the line?
Thanks in advance
the shortcode accepts parameters (attributes) and return a result (the shortcode output). If the shortcode produces a HTML then ob_start can be used to capture output and convert it to a string as follows:-
function get_posts_count( $cat ) {
ob_start();
global $wpdb;
$a = shortcode_atts( array(
'id' => '',
), $cat );
$id = $a['id'];
$count = $wpdb->get_results( "SELECT `count` FROM `wpmy_term_taxonomy` WHERE `term_id`=$id" );
foreach ( $count as $row ) {
echo '(' . $row->count . ')';
}
return ob_get_clean();
}
add_shortcode( 'postCount', 'get_posts_count' );

Wordpress remove shortcode and save for use elsewhere

Trying to remove the gallery shortcode from the post content and save in a variable for use elsewhere in the template. The new Wordpress gallery tool is great for selecting which images they want and assigning captions, hoping to use this to create the gallery, but then pull it out of the content on the front-end.
So this little snipped works just fine for removing the gallery and reapplying formatting... however I want to save that gallery shortcode.
$content = strip_shortcodes( get_the_content() );
$content = apply_filters('the_content', $content);
echo $content;
Hoping to save the shortcode so it can be parsed into an array and used to recreate a custom gallery setup on the front-end. An example of this shortcode I'm trying to save is...
[gallery ids="1079,1073,1074,1075,1078"]
Any suggestions would be greatly appreciated.
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcode
function get_shortcode_gallery ( $post = 0 ) {
if ( $post = get_post($post) ) {
$post_gallery = get_post_gallery($post, false);
if ( ! empty($post_gallery) ) {
$shortcode = "[gallery";
foreach ( $post_gallery as $att => $val ) {
if ( $att !== 'src') {
if ( $att === 'size') $val = "full"; // Set custom attribute value
$shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value")
}
}
$shortcode .= "]";
return $shortcode;
}
}
}
// Example of how to use:
echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns content
function strip_shortcode_gallery( $content ) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
// Example of how to use:
$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content
$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returns
echo $content;
just use the get_shortcode_regex():
<?php
$pattern = get_shortcode_regex();
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);
?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?php
echo do_shortcode($shortcodes[0][1]);
?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php
$content = $post->post_content;
$content = str_replace($shortcodes[0][1],'',$content);
?>
Something like $gallery = do_shortcode('[gallery]'); might work.

How to Fetch the Shortcode Parameters Value in WordPress?

[amazon_s3 bucket=my_bucket_name object=my_file_name.ext]
Hi all i need to know how to fetch the parameter value in the above shortcode. For Example: Object is the attributes then how can i fetch the object value my_file_name.ext. I am using the woocommerce s3 plugin. I am not sure i customized the woocommerce to fetch the file name show in my account page here is the code.
function filename_wc_downloads( $link, $download )
{
$order = new WC_Order( $download['order_id'] );
$download_file_urls = $order->get_downloadable_file_urls(
$download['product_id'],
null,
$download['download_id']
);
foreach( $download_file_urls as $key => $value )
{
if( $value == $download['download_url'] )
{
$url_parts = explode( '/', parse_url( $key, PHP_URL_PATH ) );
$file_name = end( $url_parts );
$link = '<a href="'
. esc_url( $download['download_url'] )
. '">'
. $download['download_name']
. '</a> <small>( '
. $file_name
. ' )</small>';
}
}
return $link;
}
In a Woocommerce all products are uploaded into the media library of upload folder. The above code is to fetch the filename show in my account page if they using direct file path. If i pasted the above shortcode in the product url, that above code doesn't help to fetch the filename. so i need to know from the shortcode how can i get the object value based on this to show the file name.
amazon_s3 is your shortcode containing $atts bucket and object
when you use wordpress function add_shortcode('amazon_s3', 'your_function_name');
it automatically converts your attributes defined in [amazan_s3 .... to $atts
e.g.
function your_funnction_name($atts) {
extract(shortcode_atts(array(
'bucket' => '',
'object' => ''
), $atts));
return $object;
}

Wordpress custom metabox input value with AJAX

I am using Wordpress 3.5, I have a custom post (sp_product) with a metabox and some input field. One of those input (sp_title).
I want to Search by the custom post title name by typing in my input (sp_title) field and when i press add button (that also in my custom meta box), It will find that post by that Title name and bring some post meta data into this Meta box and show into other field.
Here in this picture (Example)
Search
Click Button
Get some value by AJAX from a custom post.
Please give me a example code (just simple)
I will search a simple custom post Title,
Click a button
Get the Title of that post (that i search or match) with any other post meta value, By AJAX (jQuery-AJAX).
Please Help me.
I was able to find the lead because one of my plugins uses something similar to Re-attach images.
So, the relevant Javascript function is findPosts.open('action','find_posts').
It doesn't seem well documented, and I could only found two articles about it:
Find Posts Dialog Box
Using Built-in Post Finder in Plugins
Tried to implement both code samples, the modal window opens but dumps a -1 error. And that's because the Ajax call is not passing the check_ajax_referer in the function wp_ajax_find_posts.
So, the following works and it's based on the second article. But it has a security breach that has to be tackled, which is wp_nonce_field --> check_ajax_referer. It is indicated in the code comments.
To open the Post Selector, double click the text field.
The jQuery Select needs to be worked out.
Plugin file
add_action( 'load-post.php', 'enqueue_scripts_so_14416409' );
add_action( 'add_meta_boxes', 'add_custom_box_so_14416409' );
add_action( 'wp_ajax_find_posts', 'replace_default_ajax_so_14416409', 1 );
/* Scripts */
function enqueue_scripts_so_14416409() {
# Enqueue scripts
wp_enqueue_script( 'open-posts-scripts', plugins_url('open-posts.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );
# Add the finder dialog box
add_action( 'admin_footer', 'find_posts_div', 99 );
}
/* Meta box create */
function add_custom_box_so_14416409()
{
add_meta_box(
'sectionid_so_14416409',
__( 'Select a Post' ),
'inner_custom_box_so_14416409',
'post'
);
}
/* Meta box content */
function inner_custom_box_so_14416409( $post )
{
?>
<form id="emc2pdc_form" method="post" action="">
<?php wp_nonce_field( 'find-posts', '_ajax_nonce', false); ?>
<input type="text" name="kc-find-post" id="kc-find-post" class="kc-find-post">
</form>
<?php
}
/* Ajax replacement - Verbatim copy from wp_ajax_find_posts() */
function replace_default_ajax_so_14416409()
{
global $wpdb;
// SECURITY BREACH
// check_ajax_referer( '_ajax_nonce' );
$post_types = get_post_types( array( 'public' => true ), 'objects' );
unset( $post_types['attachment'] );
$s = stripslashes( $_POST['ps'] );
$searchand = $search = '';
$args = array(
'post_type' => array_keys( $post_types ),
'post_status' => 'any',
'posts_per_page' => 50,
);
if ( '' !== $s )
$args['s'] = $s;
$posts = get_posts( $args );
if ( ! $posts )
wp_die( __('No items found.') );
$html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>';
foreach ( $posts as $post ) {
$title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' );
switch ( $post->post_status ) {
case 'publish' :
case 'private' :
$stat = __('Published');
break;
case 'future' :
$stat = __('Scheduled');
break;
case 'pending' :
$stat = __('Pending Review');
break;
case 'draft' :
$stat = __('Draft');
break;
}
if ( '0000-00-00 00:00:00' == $post->post_date ) {
$time = '';
} else {
/* translators: date format in table columns, see http://php.net/date */
$time = mysql2date(__('Y/m/d'), $post->post_date);
}
$html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
$html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n";
}
$html .= '</tbody></table>';
$x = new WP_Ajax_Response();
$x->add( array(
'data' => $html
));
$x->send();
}
Javascript file open-posts.js
jQuery(document).ready(function($) {
// Find posts
var $findBox = $('#find-posts'),
$found = $('#find-posts-response'),
$findBoxSubmit = $('#find-posts-submit');
// Open
$('input.kc-find-post').live('dblclick', function() {
$findBox.data('kcTarget', $(this));
findPosts.open();
});
// Insert
$findBoxSubmit.click(function(e) {
e.preventDefault();
// Be nice!
if ( !$findBox.data('kcTarget') )
return;
var $selected = $found.find('input:checked');
if ( !$selected.length )
return false;
var $target = $findBox.data('kcTarget'),
current = $target.val(),
current = current === '' ? [] : current.split(','),
newID = $selected.val();
if ( $.inArray(newID, current) < 0 ) {
current.push(newID);
$target.val( current.join(',') );
}
});
// Double click on the radios
$('input[name="found_post_id"]', $findBox).live('dblclick', function() {
$findBoxSubmit.trigger('click');
});
// Close
$( '#find-posts-close' ).click(function() {
$findBox.removeData('kcTarget');
});
});

Resources