I am using a custom shortcode plugin. The plugin allows me to run some php. The php queries a non-wp database to build a page of vehicle specs and everything works great. The issue is that all of the information needed for the page title and description is contained within the data coming from the database. I've tried some of the standard wp php filters but the title does not change.
Is this not possibly because of the execution timing of the shortcode?
TinyMCE in WP admin. Shortcode
-----------------------------------------------
[myplugin data_id='42']
PHP window in shortcode editor
-----------------------------------------------
$GP=array_merge($_GET, $_POST);
echo "hello word" //works
echo $data_id; //works
echo $GP[some_post_data]; //works
//connect to database (irrelevant)
echo "the title from data table for data_id 42 = ".$data[title]; //works
// the following has no effect on page title even though $data[title] contains valid data
add_filter('the_title','myCallback');
function myCallback($data){
return $data[title];
}
The problem is that $data[title] is out of scope, and that your filter callback is set up incorrectly. Also, you SHOULD encapsulate associative indexes with quotes.
When adding a callback to an existing filter, the arguments within the callback are passed by the filter definition. Case and point: Filtering The Title
The arguments within a standard filter for the_title are $title and $id. If you want to return the title from your $data array, you can do it the sloppy way using the global scope:
add_filter('the_title','myCallback');
function myCallback($title, $id){
global $data;
return $data['title'];
}
But personally, I would look into avoiding globals altogether and concentrate on utilizing custom filters. Look into Adding Your Own Hooks. After getting a handle on action hooks, Filter Hooks are pretty easy to grasp.
Related
I'm using WP 5.3 with the default (Gutenberg) editor along with the Polylang 2.7.2 plugin for making the site multilingual. Using Polylang, each post consists of one translation post per language (Polylang groups translation posts together).
Now I have the following problem: When a user is writing a post and tries to link to another already existing post, the search drop down for linking text (Ctrl+K) shows posts in all available languages. If the post title isn't language-specific (e.g., "Smart Home") but the "Smart Home" post exists in two languages, it's trial and error for the user to select the one matching the language of the currently edited post:
I wanted this URL popover drop down to either only list posts of the same language as the current post, or modifying the results in the drop down to show the specific language (by flag, or "[en]" before the title).
First, I tried using the admin menu bar "Filter content by language" drop down to limit it to English posts - didn't affect the drop down at all.
Next, I tried using a filter to tamper with the query results for this drop down. Using pre_get_posts and setting the language hard-coded to English worked:
add_filter('pre_get_posts', [self::class, 'filterQueryLanguage']);
}
public static function filterQueryLanguage($query) {
$query->set('lang', 'en'); // this limits the drop down results to English posts
return $query;
}
The search drop down then only listed English posts. Unfortunately, this limits all queries and it's impossible in the filter function to know for sure if this query originated from an AJAX request by this popover drop down.. also, I didn't manage to detect the language of the currently edited post (pll_current_language() returned false in this case).
Therefore, I need a way to post-filter the results only for this popover drop down and prepend the language to the post name in some way. But I have no idea if there even is a filter for this. get_posts doesn't seem to fire and even if it did, I don't want to affect all queries.
Are there any more specific filters for this purpose?
Okay, found a solution myself. The problem is: this URL popover does a REST API query for search=phrase. This search query also has a lang= argument that is already set to the appropriate post language - however, when assembling the REST response this lang argument is ignored.
I post-filtered the REST result like so:
add_filter('rest_pre_echo_response', [self::class, 'filterRESTResponse'], 10, 3);
}
public static function filterRESTResponse($result, $server, $request) {
$params = $request->get_params();
if (!empty($params['search']) && !empty($params['lang'])) {
$filtered = [];
$lang = $params['lang'];
foreach ($result as $post) {
$post_lang = pll_get_post_language($post['id']);
if ($post_lang === $lang) {
$filtered []= $post;
}
}
$result = $filtered;
}
return $result;
}
This solution is a bit awkward as it might've been possible to make the REST query respect the language from the start. Not sure how to hook into that one, tho.
Well, whatever works.
I'm using the unyson Framework for WordPress and currently using page options which work just fine on that particular page.
But I want to be able to access those options when on another page.
Here is my php -
$page = fw()->theme->get_options( 'service-settings' );
<?php echo wp_kses_post($page['service']['options']['service-box']['options']['description']; ?>
But this doesn't allow me the content from the array.
Using the following I can see the array, but cannot get the data.
fw_print($page);
Thanks guys
You're receiving just options array by calling fw()->theme->get_options('slug') - literally what you typed in the framework-customizations/theme/options/slug.php file.
If you want to receive the actual data you need to use DB helpers.
$data = fw_get_db_settings_option();
// or even refer to individual options, for performance's sake
$individual_option = fw_get_db_settings_option('option_id');
fw_print($data);
fw_print($individual_option);
I'm using Contact Form 7 in a wordpress site with multiple forms.
I need to direct one form to a different form action url than the others.
I found the reply below for a previous thread but I'm not sure how to go about it.
Can someone specify what exact code needs to be included in "additional settings"
and what the code in functions.php would look like?
Thanks for your help!
reply from diff. thread, which I don't completely understand...
*Yes, you have to change the "action" attribute in the form using this Filter Hook wpcf7_form_action_url. (what would be the code?) You could add the hook into your theme's functions.php and then just process the form data in your ASP page.(code?) *
Since you're not familiar with PHP code at all, I'll give you a bit of a crash course in coding within the Wordpress API.
First off, you need to know the difference between functions and variables. A variable is a single entity that is meant to represent an arbitrary value. The value can be anything. A number, somebody's name, or complex data.
A function is something that executes a series of actions to either send back - or return - a variable, or alter a given variable.
<?php
$a = 1; //Number
$b = 'b'; //String *note the quotes around it*
$c = my_function(); //Call to a function called my_function
echo $a; //1
echo $b; //b
echo $c; //oh, hello
function my_function()
{
return 'oh, hello';
}
?>
Wordpress utilizes its own action and filter system loosely based on the Event-Driven Programming style.
What this means is that Wordpress is "listening" for a certain event to happen, and when it does, it executes a function attached to that event (also known as a callback). These are the "Actions" and "Filters". So what's the difference?
Actions are functions that do stuff
Filters are functions that return stuff
So how does this all fit in to your problem?
Contact Form 7 has its own filter that returns the URL of where information is to be sent by its forms.
So lets look at the basics of a Filter Hook
add_filter('hook_name', 'your_filter');
add_filter is the function that tells Wordpress it needs to listen
for a particular event.
'hook_name' is the event Wordpress is listening for.
'your_filter' is the function - or callback - that is called when the 'hook_name' event is fired.
The link to the previous thread states that the hook name you need to be using is 'wpcf7_form_action_url'. That means that all you have to do is make a call to add_filter, set the 'hook_name' to 'wpcf7_form_action_url', and then set 'your_filter' to the name of the function you'll be setting up as your callback.
Once that's done, you just need to define a function with a name that matches whatever you put in place of 'your_filter', and just make sure that it returns a URL to modify the form action.
Now here comes the problem: This is going to alter ALL of your forms. But first thing's first: See if you can get some working code going on your own. Just write your code in functions.php and let us know how it turns out.
UPDATE:
The fact that you were able to get it so quickly is wonderful, and shows the amount of research effort you're putting into this.
Put all of this in functions.php
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url()
{
return 'wheretopost.asp';
}
As mentioned before, that will affect ALL of your forms. If this is only supposed to affect a form on a given page, you can do something like this:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
global $post;
$id_to_change = 1;
if($post->ID === $id_to_change)
return 'wheretopost.asp';
else
return $url;
}
All you would need to do is change the value of $id_to_change to a number that represents the ID of the Post/Page you're trying to affect. So if - for example - you have an About Page that you would like to change the Action URL, you can find the ID number of your About Page in the Admin Dashboard (just go to the Page editor and look in your URL for the ID number) and change the 1 to whatever the ID number is.
Hope this helps you out, and best of luck to you.
Great answer #maiorano84 but I think you should check form ID instead of Post. Here is my version.
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$wpcf7 = WPCF7_ContactForm::get_current();
$wpcf7_id = $wpcf7->id();
$form_id = 123;
return $wpcf7_id == $form_id? '/action.php' : $url;
}
Another thing you might need to disable WPCF7 AJAX. That can be disabled by placing the following code in your theme functions.php
apply_filters( 'wpcf7_load_js', '__return_false' );
You can add actions after a successful submission like the documentation says
Adding a filter will work in the sense that it will change the action on the form but unfortunately it will also break the functionality of the plugin. If you add the filter like other answers suggest the form will keep the spinner state after submission.
You can make the form do something else on submit by using advanced settings such as:
on_submit: "alert('submit');"
more details about advanced settings here.
According to #abbas-arif, his solution works great, but have a limitation. This solution change the form's action on all forms present in post with that ID.
A better solution should be to use directly the form's ID. To get it, whit wordpress >5.2, you can use:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$cf7forms = WPCF7_ContactForm::get_current();
$Form = $cf7forms -> id;
switch($Form){
case 1:
return 'destination like salesforce url 1...';
case 2:
return 'destination like salesforce url 2...';
case 3:
return 'destination like salesforce url 3...';
default:
return $url;
}
}
I want to set custom php variables that can be used throughout my drupal theme (html.tpl.php, page.tpl.php etc.) I need the variables set based on the $title of the node. I'm not an expert on how Drupal works, the moduling and hooks, and I just need to know the simplest/easiest way to accomplish this. I keep reading about implementing some sort of hook in the template.php file where you can set variables, but I've been unsuccesful with everything I've tried.
So, basically, how would you accomplish this:
Get $title of Node
Set variables that will be passed along into theme files (for example, to do basic things like: if($title == 'news_page') { $siteSection = "news"; } )
Have $siteSection be available to use in theme files
Any help would be great.. thanks!
Before Drupal builds the HTML for a page from a theme's template (.tpl.php file), it runs preprocess "hooks". Hooks are basically a naming convention for functions that let modules and themes override or "hook" onto Drupal core processes.
E.g., if you want to display a message to a user when they log in, you can use hook_user_login.
function MODULENAME_user_login(&$edit, $account) {
drupal_set_message("Welcome, ". $account->name);
}
When a user logs in, Drupal looks for all loaded functions that end in "_user_login" and it runs them. If this function is in an enabled module, it has been loaded, so it will get run as well.
If you want to make a variable named $site_section available in your page.tpl.php file, you can hook into template_preprocess_page. This is a theme hook, so the name is a little different, but it functions pretty much the same way. To call this hook from your theme, you need to create a file called template.php in your theme's directory. Inside template.php, we'll add:
<?php
function THEMENAME_preprocess_page(&$vars){
switch (drupal_strtolower($vars['node']->title)) {
case "about page":
$site_section = "about";
break;
case "news page":
case "news page1":
case "news page2":
$site_section = "news";
break;
default:
$site_section = "none";
break;
}
$vars['site_section'] = $site_section;
}
The <?php is used to tell the server the treat all of the proceeding code as PHP. We then declare our hook function with the intention of loading Drupal's array of page variables into a local variable called $vars. By adding the & before $vars, we'll be allowed to modify the values for use outside of this function.
The switch statement will let us efficiently test the page title for multiple values. The value of the node's title may contain uppercase letters, lowercase letters, and symbols, so to avoid a case-sensitive mismatch, we're going to convert the title to lowercase and only test that (symbols will still be in the title, though). After the switch statement, we set the value of our $site_section local value into the referenced $vars array for use in page.tpl.php.
However, if it's just your intention to break the site up into sections for theming purposes, there are other ways of accomplishing that. My answer to a similar situation a few months ago might be helpful.
I've created a calendar plugin and now I want to show a event list in one of my templates.
The code I'm using now, is this:
include_once(WP_CAL_PLUGIN_DIR.'eventcal.class.php');
$calendar = new EventCalendar();
$events = $calendar->getMultipleEvents('5');
(...)
<table>
<?php foreach($events as $event) : ?>
<tr>
<td><span><?php echo $calendar->formatEventTime($event->startTime,'dm'); ?></span></td>
<td><span><?php echo $calendar->formatEventTime($event->startTime,'time'); ?></span></td>
<td><?php echo $event->name; ?></td>
</tr>
<?php endforeach; ?>
</table>
Is there a way I can call functions within my plugin without having to include the WP plugin and creating a new class instance?
In order to execute shortcode inside a template, use the function do_shortcode('[my-shortcode-handle]'). Your shortcode needs to be registered as like normal (see WordPress codex on shortcode API) before you can use this in the template. Any attributes, inside content, etc. should be in there as well.
echo do_shortcode( '[my-shortcode foo="bar"]Shortcode content[/my-shortcode]' );
Also, remember to echo the return (or at least assign it to a variable), since it only returns the shortcode's output.
From: http://codex.wordpress.org/Plugin_API
Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:
Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.
Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.
Actions
Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying a page of the admin panel. Your plugin can respond to the event by executing a PHP function, which might do one or more of the following:
* Modify database data
* Send an email message
* Modify what is displayed in the browser screen (admin or end-user)
The basic steps to making this happen (described in more detail below) are:
Create the PHP function that should execute when the event occurs, in your plugin file.
Hook to the action in WordPress, by calling add_action()
Put your PHP function in a plugin file, and activate it.
EXAMPLE:
function email_friends($post_ID) {
$friends = 'bob#example.org,susie#example.org';
mail($friends, "sally's blog updated",
'I just put something on my blog: http://blog.example.com');
return $post_ID;
}
Hook to WordPress
After your function is defined, the next step is to "hook" or register it with WordPress. To do this, call add_action() in the global execution space of your plugin file:
add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );
where:
hook_name
The name of an action hook provided by WordPress, that tells what event your function should be associated with.
your_function_name
The name of the function that you want to be executed following the event specified by hook_name. This can be a standard php function, a function present in the WordPress core, or a function defined by you in the plugin file (such as 'email_friends' defined above).
priority
An optional integer argument that can be used to specify the order in which the functions associated with a particular action are executed (default: 10). 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.
accepted_args
An optional integer argument defining how many arguments your function can accept (default 1), useful because some hooks can pass more than one argument to your function. This parameter is new in release 1.5.1.
In the example above, we would put the following line in the plugin file:
add_action ( 'publish_post', 'email_friends' );