I was creating a wordpress plugin where the user enters in some information, and is able to generate shortcodes. I was not quite sure where the shortcodes are supposed to go - my current setup is class-based, and I want to be able to create a shortcode when an AJAX request is being made, and is successful. The following two methods are in the same file in the class.
This method gets called via the admin-ajax.php file:
public static function processAjax()
{
global $wpdb;
$event_data = $_POST['obj'];
$event_title = $event_data[0];
$event_subdomain = $event_data[1];
$result_events = $wpdb->get_results("SELECT * FROM wp_shortcode_plugin WHERE subdomain = '{$event_subdomain}'", OBJECT);
if (sizeof($result_events)>0) {
echo "duplicate";
} else {
add_shortcode($event_subdomain, 'getEmbed');
$results = $wpdb->insert('wp_shortcode_plugin', array("event_name"=>$event_title, "subdomain"=>$event_subdomain));
echo json_encode($_POST['obj']);
}
die();
}
And here is my getEmbed() method that I would like to call.
public static function getEmbed()
{
return 'test';
}
It seems that the shortcodes are not being created, however. Am I missing something here? Also, is it possible to pass a value to the getEmbed function from the add_shortcode() method?
Instead of adding shortcode directly from AJAX, you should use update_option to store in the information for the shortcode to be loaded. If option doesn't exist, it will be created.
Than you will simple use wp_init hook to load up all of the shortcodes you need to load in the function.php file for the theme or plugin php file.
You should use get_option within the wp_init hook and check the values in there. You will need to have function(s) associated with the shortcodes, which can be autogenerated in php using create_function or you can route them through 1 function (defined in your php file) that will have the $atts and $content parameters defined and do whatever depending on the value of your get_option that you send to that function.
add_shortcode function should be defined within the wp_init hook, after checking the value of the get_option function. You will need to give your option a name and add to it via the ajax function. the option will most likely want to be an array, that wordpress will automatically serialize. Than you use that array returned from get_option to loop through the array of shortcodes, and call add_shortcode as many times as you need there. This requires setting up your option array so that it has a shortcode tag defined in each index of the array. I would, personally, make the shortcode tag the key of the array and all attributes of the shortcode, imo, would than be an array of that array.
Hope this helps you to get started on this.
Related
I want to create a nice readable permalink structure for my custom post type (CPT). My CPT "movie" has the following rewrite-slug movie/movie_name" (all works fine).
Now i want to add arg like this: movie/movie_name/arg and use arg in my template file as a php variable.
But obvious it lead to not-found-page. How can i achieve this target?
edit: i want it in FRIENDLY URL format, it means i dont want to use GET for this.
You may pass it like movie/movie_name?movie_arg=movie_value. It is will be available with $_GET['movie_arg']. Of course your need extra sanitization to handle this data.
To be able to read this in a WordPress way add params to a query_vars filter
function add_movie_arg_to_query_vars( $qvars ) {
$qvars[] = 'movie_arg';
return $qvars;
}
add_filter( 'query_vars', 'add_movie_arg_to_query_vars' );
Note: it should not be same as reserved WordPress query parameters
This way it will be available at your template with get_query_var('movie_arg')
print_r( get_query_var('movie_arg') ) // movie_value
More information here
I followed the syntax the best I could to create a shortcode on execution, I got the wsod. Once removed, all was well. But I don't know what is wrong with my code. This code sits inside 'My Custom Functions', a plugin for wp.
In researching how to write a custom shortcode, I discovered instructions here: https://torquemag.io/2017/06/custom-shortcode/ My expertise is in mysql and use mostly plugins in our wordpress website. I am very limited with coding.
function last_updated_shortcode {
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM
qgotv.last_updated");
return $last_updated;
}
add_shortcode( 'last_updated', 'last_updated_shortcode' );
This shortcode should retrieve a max(datetime value) from a db table so it can be displayed on a page. The query works. The qgotv db is separate from the wordpress db but can be accessed through wp.
Two issues I can see, one is that you have a syntax error in your function. When defining a function in PHP, you need to include the arguments parenthesis: function my_function(){ /* Do Stuff */ }. Also, you probably need to reference the $wpdb with the global keyword.
You can read up a bit on the $wpdb class as well as creating your own functions.
This should get you sorted out:
add_shortcode( 'last_updated', 'last_updated_shortcode' );
function last_updated_shortcode(){
global $wpdb;
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM qgotv.last_updated");
return $last_updated;
}
I'm trying to override the output in the footer of a Wordpress theme. The given section just has a do_action('action_name')
In my functions.php I've added:
add_action('action_name', 'action_name');
function action_name() {
echo "<p>Additional text</p>";
}
However, this outputs the content I wish to replace along with the content I want to add. I'm fairly new to themeing Wordpress so I'm fairly lost here. What am I doing wrong?
If you can find which function is doing the output you want to remove you can use remove_action() to remove it:
remove_action( $tag, $function_to_remove, $priority );
To find this you will have to look through the code of the theme or plugin that generates it. Somewhere will be a add_action() call similar to yours. Note the function name and priority and use remove_action() along with it in your plugin/theme.
The hard solution would be to remove all functions for that action with remove_all_actions().
Afterwards you can add your own output as you are doing now.
Note: Be mindful that using remove_all_actions() is not advisable on all actions. For example, the action wp_footer is used to load JavaScript at the end of the page. Removing all functions there will render plugins and themes that depend on it useless.
Check add_action related code here-
add_action ( string $tag, callable $function_to_add, int $priority =
10, int $accepted_args = 1 )
$tags (string) (Required) The name of the action to which the
$function_to_add is hooked.
$function_to_add (callable) (Required) The name of the function you
wish to be called
$priority (int) (Optional) Used to specify the order in which the
functions associated with a particular action are executed. Lower
numbers correspond with earlier execution, and functions with the same
priority are executed in the order in which they were added to the
action. Default value: 10
$accepted_args (int) (Optional) The number of arguments the function
accepts. Default value: 1
Have a look over below thread hope this will help you-
https://developer.wordpress.org/reference/functions/add_action/
In Wordpress (now in Template Fiile), lets say i have a custom Shortcode function, like:
In the PAGE:
[myshortcode id='1234']
Then, in the Template File:
function parseUserID_func( $atts ){
//parse the $atts here...
$userID = 1234; //now i get the userID is, 1234
}
add_shortcode( 'myshortcode', 'parseUserID_func' );
//now .. echo the value of $userID here? <----------
printout_UserDetails( $userID );
As you can see, how can i get the processed value of $userID variable out from the shortcode function please? (as in the last line)
The $userID is not touchable from the outside.
Actually what i'm trying to do is something like:
Pass an ID from the Page, using [myshortcode id="1234"]
Parse out the id from the shortcode's function. (parseUserID_func above)
When i get the id, i need to pass it to another custom function printout_UserDetails($id){} function (written in the Template File) .. to continue another processing works.
(Something like) then i will print out the USER DETAILS on the Page, from the printout_UserDetails() function.
This is why i need to pass a value from Shortcode, then parse it, then pass the id to my another custom function.
Any help please?
From what I'm understanding you're not trying to generate output with the shortcode, but to save data instead. I would try using custom fields to handle this.
If you need to output the "USER DETAILS" block within the post content (right where the shortcode is written), you should just merge the printout_userDetials logic into the actual shortcode handler function itself (in this case parseUserID_func).
I have an issue with triming a field before it is saved. I wanted to use substr(), or regex() with preg_match(). I have built a Drupal 7 module, but it can't work at all. I have tried using the trim plugin in feeds tamper module, but it doesn't seem to work. The data I am using is from a feed from Google Alerts. I have posted this issue here.
This is what I have done so far, and I know my regular expression is wrong; I was trying to get it do anything, just to see if I could get it to work, but I am pretty lost on how to add this type of function to a Drupal module.
function sub_node_save() {
$url = $node->field_web_screenhot['und'][0]['url'];
$url = preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i',$url );
$node->field_web_screenhot['und'][0]['url'] =$url;
return ;
}
I used the Devel module to get the field.
If there's an easy way to use substr(), I would consider that or something else.
Basically, I just want to take the Google redirect off the URL, so it is just the basic URL to the web site.
Depending on your question and later comments, I'd suggesting using node_presave hook (http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7) for this.
It's called before both insert (new) and update ops so you will need extra validations to prevent it from executing on node updates if you want.
<?php
function MYMODULE_node_presave($node) {
// check if nodetype is "mytype"
if ($node->type == 'mytype'){
// PHP's parse_url to get params set to an array.
$parts = parse_url($node->field_web_screenhot['und'][0]['url']);
// Now we explode the params by "&" to get the URL.
$queryParts = explode('&', $parts['query']);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
//valid_url validates the URL (duh!), urldecode() makes the URL an actual one with fixing "//" in http, q is from the URL you provided.
if (valid_url(urldecode($parms['q']))){
$node->field_web_screenhot['und'][0]['url'] = urldecode($parms['q']);
}
}
}