Inserting Wordpress Plugin content to posts - wordpress

I am trying to learn more about Wordpress and creating plugins. I have seen an existing plugin use a technique where you can add a 'reference' to it within your posts and WP will parse it and replace it with the plugins own content. The example i am referring to is the NextGen gallery which uses the following code
[nextgen id=9]
I have tried searching for how this technique works but trying to find something that you don't know the name of is pretty difficult!
Can anyone point me towards some resources about how to use this feature of WP?

The technique is called shortcodes.
add_shortcode('my-content','my_plugin_shortcode');
function my_plugin_shortcode($atts, $content = null) {
$atts = shortcode_atts($my_default_atts,$atts); // $atts is now an associate array
$my_content = 'This is some content.';
return $my_content;
}
Then, if you have a post with the following content:
Hey, here is some content.
[my-content]
You will get the following output when the post is displayed:
Hey, here is some content. This is
some content.
If you passed a shortcode like [my-content id="9" test="test"], then the $atts variable in the above function would be like the following array declaration
$atts = array('id'=>9, 'test'=>'test');
The $content variable only has content when you use matching shortcodes around some text:
[my-content]This is some test
content.[my-content]

Related

Can I display a custom field inside a Loop Query block?

I’m fairly new to Wordpress and I’m trying all my best to learn, but I can’t find a solution for this one…
I’ve been using the Twenty Twenty-Two theme and I’ve added a custom field ("city") to my articles.
Of course when I add a Query Loop block on my homepage, the visual editor allows me to use Titles, Categories and so on… but it won’t let me use my custom field.
I tried adding what follows to functions.php:
add_shortcode( 'city', 'return_my_custom_value' );
function return_my_custom_value() {
$myCity = do_shortcode(get_post_meta(get_the_ID(), 'city', true));
return $myCity;
}
But it won’t work, because then I use the following shortcode inside my Query Loop block:
[city]
and it shows a list of my articles all with the same 'city' value, repeated — which is the one I assigned to the page I’m showing the query on (my homepage).
Any solution for this? I would really appreciate each suggestion. Thank you so much in advance!
We have checked the code you are not calling shortcode inside the query loop. we have updated the code you can use the code. Please check below the updated code and add in the functions.php file.
add_shortcode( 'city', 'return_my_custom_value' );
function return_my_custom_value() {
$myCity = get_post_meta(get_the_ID(), 'city', true);
return $myCity;
}
Please use the following shortcode inside your query loop block
echo do_shortcode('[city]');

Add specific words to WordPress custom type slug

I have a WordPress installation with a custom type (places) wich produces this permalink structure:
http://example.com/places/the-first-site/
And I would like to show all my sites like this:
http://example.com/places/visit-the-first-site-and-enjoy/
where 'visit' and 'and-enjoy' would be always those specific words (constants).
Even better I would like to put a custom taxonomy I have (year) as a metadata
places/visit-the-first-site-and-enjoy-1985/
I can access the DB and modify the post name of all post, but I would have to do for the new post also, and I'm looking for some automated rule, but can't find how to do.
Maybe some rewrite rule, but I don't know how to do it.
Any ideas??
You do not have to edit anything in your database nor any codes in your WordPress installation; you can achieve that directly from your WordPress administration panel.
From your Dashboard, click on the Permalink sub-menu under Settings; there, you will have to select the Custom Structure option and set it as follow in order to achieve your desired effect:
/places/visit-%postname%-and-enjoy-%year%/
Please note: here, we made use of both %postname% and %year% Structure Tags so as to get names of posts with their corresponding year of publication respectively.
Don't forget to click on the Save Changes button on the page in order to effect your changes.
... Read more on Permaklinks (for general knowledge).
For a custom post type and taxonomies as expressed further in comments, you will need a custom solution which will require a little bit of coding and or tweaking, depending on your abilities; you may use this handy plugin (Custom Post Type Permalinks) from the WordPress.org Plugins repository.
This posts should equally be of great help to you, to getting started and understanding further, should you chose to code.
You have différent hook like save_post or pending_to_publish, where you can set or change the "post_name" (that's corresponds to the permalink slug).
To Add specific words to WordPress custom type slug You have to Register custom rewrite rules.
suppose this is Your URL http://example.com/places/the-first-site !
and you have a post type places.
function add_rewrite_rules()
{
$wp_rewrite->add_rewrite_tag('%places%', '([^/]+)', 'places=');
$wp_rewrite->add_rewrite_tag('%state%', '([^/]+)', 'state=');
$wp_rewrite->add_permastruct('places', 'places/visit-%state%-and-enjoy/', false);
}
function permalinks($permalink, $post, $leavename)
{
$no_data = 'no-data';
$post_id = $post->ID;
if($post->post_type != 'story' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;
$state = get_post_meta($post_id, 'location', true);
if(!$state)
$state = $no_data;
$permalink = str_replace('%state%', $state, $permalink);
return $permalink;
}
add_action('init', 'add_rewrite_rules');
add_filter('post_type_link', 'permalinks', 10, 3);
put this code in your custom post type plugin. and if get page not found error please change your permalink setting. or make a custom template file to show this post.

Where can I add another class for woocommerce wrapper?

Woocommerce have a div with a class "woocommmerce" I want to add another class or remove the class. Which file is that?
<div class="woocommerce"></div>
Although there isn't any supported method provided by WooCommerce for achieving that, you could "hack" on the function which builds the wrapper directly.
The problem
<div class="woocommerce"></div>
"The master wrapper". Almost all things WooCommerce lives within it.
WooCommerce plugin kind of "protects" its main wrapper as it depends on it for doing all kinds of stuff (styling, js functionality) etc. For that reason, the plugin hasn't a filter available so one could hook to and override it.
By the way, it is not recommend to remove it, one would rather add additional css classes to it, which is possible.
There's even a Github issue which seems to state that WooCommerce "Won't fix" it (at least for now).
Use cases
Amongst all possible use cases that might be out there, mine was to apply additional css classes to the wrapper <div class="woocommerce"></div> to fit my theme's CSS framework, (Bootstrap 4) specifically.
I simply wanted it to become <div class="woocommerce container-fluid container-application"></div>
BUT
How to safely change it?
Inspecting it further
Looking at WooCommerce's class-wc-shortcodes.php under the includes/ directory, let's go ahead and dissect it. If you jump to this line you can have a glimpse at the shortcode_wrapper() function, which builds that "annoying" wrapper. Jump here to see an array of woocommerce shortcode slugs, which will have their contents wrapped within the <div class="woocommerce"></div>.
Or according to my own use case, on this specific line, My Account page shortcode is returned within the shortcode_wrapper() function, which again results in all the My Account pages' contents living within the <div class="woocommerce"></div>.
That is also true for other shortcodes used by WooCommerce, so go ahead to the solution part and you might be able to change the wrapper while on other WooCommerce pages other than the My Account.
The Solution (!)
"shut that whole thing down"
We're going to hack on the function which builds the <div class="woocommerce"></div> directly.
We have to create a new shortcode by calling the WC_Shortcodes() class. It will kind of "redirect" all the contents from a specific WooCommerce shortcode to our newly created one.
Now, the following function specifically targets the My Account pages, but it could be easily adapted to conditionally target other pages containing the WooCommerce shortcodes.
So, the default WooCommerce pages as most of you might be aware of, are nothing more than ordinary WordPress pages you can manage under the Admin dashboard. However, those pages do also display the contents of the default WooCommerce shortcodes such as the [woocommerce_my_account], which is the one we'll replace later on.
Place the function bellow on your functions.php, save & upload it.
/**
* WooCommerce My Account
* Returns custom html / css class for WooCommerce default wrapper on My Account pages
* #see https://github.com/woocommerce/woocommerce/blob/857c5cbc5edc0451cf965b19788e3993804d4131/includes/class-wc-shortcodes.php#L59
*
**/
if ( class_exists( 'woocommerce' ) ) {
function wp_wc_my_account_shortcode_handler( $atts ) {
$whichClass = new WC_Shortcodes();
$wrapper = array(
'class' => 'woocommerce container-fluid container-application',
'before' => null,
'after' => null
);
return $whichClass->shortcode_wrapper( array( 'WC_Shortcode_My_Account', 'output' ), $atts , $wrapper );
}
add_shortcode( 'new_woocommerce_my_account', 'wp_wc_my_account_shortcode_handler' );
}
------------------// ------------------
Now, let's head to the My Account Page on the browser and inspect the html, you'll notice nothing has changed. That's because we now have to go to Admin >> pages >> My Account, and then replace the default WooCommerce [woocommerce_my_account] shortcode with the [new_woocommerce_my_account].
Update/Save the My Account page under the Admin Dashboard and now all the My Account pages contents will be wrapped within our new <div class="woocommerce container-fluid container-application"></div>.
Bonus
Constructing custom html for the wrapper
In case you wanted a custom html tag for the wrapper, simply passing the tag along with your css class/classes will do the job. Change the following part of the function above to:
$wrapper = array(
'class' => '',
'before' => '<section class="woocommerce container-fluid container-application>',
'after' => '</section>'
);
And now instead of a <div></div>, our wrapper will be a <section></section>.
Simply follow (enhance) the logic and you'll be able to replace the wrapper on almost all WooCommerce pages such as products, product, product categories, cart, checkout, my account and so on.
there is no ready-made filter or anything like that, that lets you do it, but you could filter the_content, to get it done.
function so33675604_add_class_to_checkout( $content ) {
//condition to check for the proper page
if ( is_checkout() ) :
//disable error reporting for falsy formatted html code
libxml_use_internal_errors(true);
//parse the $content html (treat content as UTF-8, don't add any doctype or other html wrappers)
$html = new DOMDocument();
$html->loadHTML( mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
//search for the very first div
$container = $html->getElementsByTagName('div')->item(0);
//add classes (remember to put woocommerce, since thats been used by some js functions)
$container->setAttribute('class', 'woocommerce oink');
//return the result
return $html->saveHTML();
endif;
return $content;
}
//add the filter (priority must be high, so it runs later, after the shortcodes have been processed)
add_filter( 'the_content', 'so33675604_add_class_to_checkout', 100 );
please be aware, that this function uses conditionals and these might not work in wp-ajax calls / you would have find another way to check, if checkout (or else), probably via global wp_query.

execute do_shortcode in functions.php

I'm trying to run a do_shortcode in functions.php with no luck
I'm using Types plugin http://wp-types.com/ for creating custom post types and custom fields.
What I'm trying do is adding a custom column in admin for view all custom posts that displays a thumbnail from a custom field.
This is what I got so far, but it seems that the shortcode doesn't work inside functions.php
// add a column for custom post type (products)
add_filter('manage_product_posts_columns', 'add_thumbnail_column');
add_action('manage_product_posts_custom_column', 'add_thumbnail_content', 10, 2);
function add_thumbnail_column($defaults)
{
$newSlice = array('thumbnail' => 'Image preview');
$counter = 2;
$array_head = array_slice($defaults,0,$counter);
$array_tail = array_slice($defaults,$counter);
$defaults = array_merge($array_head, $newSlice);
$defaults = array_merge($defaults, $array_tail);
return $defaults;
}
function add_thumbnail_content($column_name, $post_ID)
{
// this one works when putting into post content
echo do_shortcode('[types field="square-picture" id="' . $post_ID . '" size="thumbnail"]' . '[/types]');
}
Can anyone help please?
In the Wordpress notes for the function it says
"If there are no shortcode tags defined, then the content will be
returned without any filtering. This might cause issues if a plugin is
disabled as its shortcode will still show up in the post or content."
Types may be conditionally declaring their short code only when you are on the frontend. What may be happening is that, in the admin, the short code is not defined and you are simply getting a false return. While on the frontend, the shortcode is defined and you get the results you intended.

is there a way (plugin) to insert html/css/images ect automatically into every wordpress post?

is there a way (plugin) to insert html/css/images ect.. automatically into every wordpress post? most of my posts are going to be very similar so is there a plugin that will automatically insert the pre written html/css/ ect in every post as opposed to me entering it manually every time.
Thank you in advance ;-)
You can write your own simple function for this, see my example below:
add_filter( 'default_content', 'my_editor_content' );
function my_editor_content( $content ) {
global $post_type;
if( $post_type == 'post') { /* Or your custom post type, pages etc. */
$content = 'Your custom HTML/CSS content here';
}
return $content;
}
Place this in functions.php and it will be the default content of every new post/page/custom post type you create.
For a list of available post types, please refer to the Codex
You could use a plugin such as Ad injection, it will allow you to do what you need without having to alter / amend / ad any code to the templates or files

Resources