简体   繁体   中英

Display a wordpress shortcode in elementor widget?

I'm not familiar with WordPress yet, I want to display a shortcode in the widget itself but it shows it as #text

<li><span>[My-shortcode].. 

As I understand, I must edit the code of the custom theme, but where do I start? Maybe there are some hacks-bypasses to make it work? Plugins that auto-detect text as shortcode? If I could type PHP in Wp Editor I could make it work, any ideas?

First of all: no, you cannot type PHP code into the WP editor. The most common ways of writing custom code in WordPress are:

  1. Creating your own plugin
  2. Creating a child theme, modifying the child theme's functions.php

For the second option, please follow the official guide at https://developer.wordpress.org/themes/advanced-topics/child-themes/ .

Once you have it set up, activated, and have a custom empty functions.php file inside your child theme's directory, you can open the functions.php file and add the following code:

function mytextdomain_myshortcode($attrs = array(), $content = null)
{
  $attrs = shortcode_atts( array(
      'value' => 'content'
  ), $attrs );
  ob_start();
?>
Write your own HTML code outputting <strong>some <?= $attrs['value'] ?></strong> here!
<?php
  return ob_get_clean();
}

// add the custom shortcode:
add_shortcode('myshortcode', 'mytextdomain_myshortcode');

The mytextdomain_myshortcode callback function will be evaluated each time a shortcode is rendered. You can rename that function to whatever you want - the text domain should be something that makes the name unique. What kind of HTML you want to output depends on what you want it to do.

After this, you can use [myshortcode] , or [myshortcode value="custom text"] in any place where shortcodes are evaluated. You can add arguments depending on the functionality you want to implement. Do not use hyphens in shortcode names. You can also simply turn this into an enclosing shortcode by outputting the $content . In case of [myshortcode]This will end up in content![/myshortcode] , $content will contain everything between the shortcode tags. Or you can just decide to ignore content all along.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM