i would change the page title from a wordpress plugin site. the name comes from a function:
function subPage() {
$content = 'blabla';
$subPageTitle = 'Plugin Sub Page Dynamic';
return $content;
}
and the simple function for replace wp_title:
function wp_plugin_page_title($subPageTitle) {
$siteTitle = $subPageTitle;
return $siteTitle;
}
add_filter('wp_title', wp_plugin_page_title);
my problem is now: how i get the variable $subPageTitle in the function wp_plugin_page_title()?
Thanks a lot for ANY help!
EDIT: the code was not correct.
function subPage() {
$subPage = new stdClass();
$subPage->content = 'blabla';
$subPage->subPageTitle = 'Plugin Sub Page Dynamic';
return $subPage;
}
function wp_plugin_page_title($subPageTitle) {
$siteTitle = $subPageTitle . " " . subPage()->subPageTitle;
return $siteTitle;
}
add_filter('wp_title', wp_plugin_page_title);
Then you get the value by calling subPage()
echo subPage()->subPageTitle;
If you print_r the subpage you will see:
stdClass Object ( [content] => blabla [subPageTitle] => Plugin Sub Page Dynamic )
Any values that are inside a function, they are encapsulated values if you need to reach them outside that function or you return them in an array or in an object.
Related
I would like to prevent that some categories are accidentally deleted. For this I use a meta entry for the category to be protected.
I use the following code for this:
// edit: wrong hook! ** add_action( 'delete_term_taxonomy', 'taxonomy_delete_protection', 10, 1 );
add_action( 'pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
if (get_term_meta ($term_id, 'delete-protect', true) === true)
{
wp_die('Cannot delete this category');
}
}
Unfortunately, instead of my error message, only "Something went wrong" is displayed. Why?
Edit: The `delete_term_taxonomy` is the wrong hook for my code, because it deleted the meta before i can check the meta entry. `pre_delete_term` does fire before anything happens with the category.
The "Why" is because of the following JavaScript that ships with WordPress:
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
/**
* Removes the term from the parent box and the tag cloud.
*
* `data.match(/tag_ID=(\d+)/)[1]` matches the term ID from the data variable.
* This term ID is then used to select the relevant HTML elements:
* The parent box and the tag cloud.
*/
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Sorry, you are not allowed to do that.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Something went wrong.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
The expected response to this POST request is:
'1' if the term was deleted
'-1' if your user doesn't have permission to delete the term.
For all other cases, "Something went wrong" is displayed.
You are terminating the script early with wp_die, yielding an unexpected response, which comes under "other cases".
There isn't a way to provide a custom error message in the notice box here without writing some JavaScript of your own.
This is my current solution, not perfect but it works.
The "Something went wrong" message show up if you delete the taxonomy with the row action. So i unset the "delete" action so it couldn't be triggered this way.
add_filter ('category_row_actions', 'unset_taxonomy_row_actions', 10, 2);
function unset_taxonomy_row_actions ($actions, $term)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
unset ($actions['delete']);
}
return $actions;
}
Then i hide the "Delete" Link in the taxonomy edit form with css. It's still could be triggered if you inspect the site and it's link, but there is no hook to remove this action otherwise.
add_action( 'category_edit_form', 'remove_delete_edit_term_form', 10, 2 );
function remove_delete_edit_term_form ($term, $taxonomy)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
// insert css
echo '<style type="text/css">#delete-link {display: none !important;}</style>';
}
}
Finally the check before deleting the taxonomy. This should catch all other ways, like the bulk action "delete". I didn't found another way yet to stop the script from deleting the taxonomy.
add_action ('pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
$delete_protected = get_term_meta ($term_id, 'delete-protect', true);
if ($delete_protected)
{
$term = get_term ($term_id);
$error = new WP_Error ();
$error->add (1, '<h2>Delete Protection Active!</h2>You cannot delete "' . $term->name . '"!');
wp_die ($error);
}
}
This solution provides a way to disable all categories from being deleted by a non Admin. This is for anyone like myself who's been searching.
function disable_delete_cat() {
global $wp_taxonomies;
if(!current_user_can('administrator')){
$wp_taxonomies[ 'category' ]->cap->delete_terms = 'do_not_allow';
}
}
add_action('init','disable_delete_cat');
The easiest solution (that will automatically take care of all different places where you can possibly delete the category/term) and in my opinion the most flexible one is using the user_has_cap hook:
function maybeDoNotAllowDeletion($allcaps, $caps, array $args, $user)
{
if ($args[0] !== 'delete_term') return $allcaps;
// you can skip protection for any user here
// let's say that for the default admin with id === 1
if ($args[1] === 1) return $allcaps;
$termId = $args[2];
$term = get_term($termId);
// you can skip protection for all taxonomies except
// some special one - let's say it is called 'sections'
if ($term->taxonomy !== 'sections') return $allcaps;
// you can protect only selected set of terms from
// the 'sections' taxonomy here
$protectedTermIds = [23, 122, 3234];
if (in_array($termId, $protectedTermIds )) {
$allcaps['delete_categories'] = false;
// if you have some custom caps set
$allcaps['delete_sections'] = false;
}
return $allcaps;
}
add_filter('user_has_cap', 'maybeDoNotAllowDeletion', 10, 4);
I am facing a weird problem. I am trying to override value in a function using apply_filter.
Here is the code which I am using in the theme's functions.php file:
function customized_params_6e9668( $attrs ) {
$subfolder = isset($_GET["sub"]) ? '/'.$_GET["sub"] : '';
$attrs["folder"] = $attrs["folder"].$subfolder; // if getting the value from the url then not working in this case
//$attrs["folder"] = $attrs["folder"]."/testing"; // if I use static name then working in this case
echo $attrs["folder"];
return $attrs;
}
add_filter( "customized_params_6e9668", "customized_params_6e9668");
Here is the function where I am using apply_filter to override the values in the plugin's file.
function getFolderData(){
global $wpdb;
$folder_data = $wpdb->get_row(
$wpdb->prepare(
'SELECT * FROM ' . $wpdb->prefix . 'folders WHERE key=%s',
trim(sanitize_text_field($_REQUEST["data_key"]))
)
);
if(!empty($folder_data)){
$folder_data = apply_filters( 'customized_params_'.$folder_data->key, $folder_data );
print_r($folder_data);
}
}
This function is getting the list of data from the database. overriding the value of the folder using add_filter.
Please correct me where I am doing wrong.
Thanks in advance.
I am creating a plugin. I want to pass parameters in URL or you can say I want multiple URLs for same page(But this will load same page Not a Redirect).
For example:
http://www.ijmsbr.boxysolutions.com/publications-of-ijmsbr/?data=2016-11
I want this URL in this structure
http://www.ijmsbr.boxysolutions.com/publications-of-ijmsbr/2016-11/
and these will be multiple links like
publications-of-ijmsbr/2016-11/
publications-of-ijmsbr/2016-12/
publications-of-ijmsbr/2017-01/
But all links should load this one page
publications-of-ijmsbr/
http://www.ijmsbr.boxysolutions.com/publications-of-ijmsbr/
this is my custom page. I want to get these parameters (/2016-11/, /2016-12/) on my page.
Resolved
First we'll add filter to set query variables. Remember you've to call flush_rewrite_rules() each time when you'll add new variable in array. Once you've run flush_rewrite_rule function after that you can comment or delete this line.
function themeslug_query_vars( $qvars ) {
$qvars[] = 'jm_volume';
$qvars[] = 'jm_art_id';
$qvars[] = 'jm_author';
//flush_rewrite_rules();
return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' , 10, 1 );
After registration of query variables we can add add_rewrite_rules and assign to our URL like this. Remember to call flush_rewrite_rules() function
function add_rewrite_rules($aRules) {
$aNewRules = array(
'publications-of-ijmsbr/article/(.*)?' => 'index.php?pagename=publications-of-ijmsbr&jm_art_id=$matches[1]',
'publications-of-ijmsbr/author/(.*)?' => 'index.php?pagename=publications-of-ijmsbr&jm_author=$matches[1]',
'publications-of-ijmsbr/(.*)?' => 'index.php?pagename=publications-of-ijmsbr&jm_volume=$matches[1]'
);
$aRules = $aNewRules + $aRules;
//flush_rewrite_rules();
return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');
I'm trying to create some filters for a datalist. I'd like the user to be able to select one or multiple filters from a list of tags and then spit out a list of objects based on those filters. All is good using this code to grab data based on the URL params being sent...
public function index(SS_HTTPRequest $request)
{
// ...
if($tagsParam = $request->getVar('tags')) {
$articles = new ArrayList();
$tagids = explode(",", $tagsParam);
foreach($tagids AS $tagid) {
$tag = Category::get()->byID($tagid);
$articleitems = $tag->getManyManyComponents('Articles')->sort('Date DESC');
foreach($articleitems AS $articleitem) {
$articles->push($articleitem);
}
}
}
$data = array (
'Articles' => $articles
);
if($request->isAjax()) {
return $this->customise($data)->renderWith('ListItems');
}
return $data;
}
That code works fine with a URL like mysite.com/?tags=1,2,3
My issue comes with trying to generate that URL based on the filters built with a CheckboxSetField. Here is my code for that...
public function ArticlesSearchForm()
{
$tagsmap = $this->getTags()->map('ID', 'Title')->toArray();
$form = Form::create(
$this,
'ArticlesSearchForm',
FieldList::create(
CheckboxSetField::create('tags')
->setSource($tagsmap)
),
FieldList::create(
FormAction::create('doArticlesSearch','Search')
)
);
$form->setFormMethod('GET')
->setFormAction($this->Link())
->disableSecurityToken()
->loadDataFrom($this->request->getVars());
return $form;
}
When the user submits that form, the URL generated is something along the lines of mysite.com?tags%5B1%5D=1&tags%5B2%5D=2&action_doArticlesSearch=Search Obviously, it's passing the values as an array. How can I pass a simple comma separated list?
Rather than trying to change the return of CheckboxSetField, I'd recommend changing your code. Given you are converting the comma-separated list list into an array already here:
$tagids = explode(",", $tagsParam);
Something like this, will skip this step:
public function index(SS_HTTPRequest $request)
{
// ...
if($tagsParam = $request->getVar('tags')) {
$articles = new ArrayList();
//This has a minor risk of going bad if $tagsParam is neither an
//array of a comma-separated list
$tagids = is_array($tags) ? $tagsParam : explode(",", $tagsParam);
I have been going through the docs and source code looking for something without luck.
Is there a Drupal 6 hook that gets called after hook_search(), but before the $results gets handed off to the template system?
I need to do a fairly custom pruning and reordering of results that get returned. I could just reimplement hook_search(), but this seems like overkill.
Thanks.
There isn't; search_view() (which displays the results) calls search_data(), which invokes hook_search() then immediately themes the results. Re-implementing hook_search() is probably the most straightforward route.
With that said, you could instead implement hook_menu_alter() and have the search page call your custom function instead of calling search_view() (and subsequently calling search_data()). Something like:
function test_menu_alter(&$items) {
$items['search']['page callback'] = 'test_search_view';
foreach (module_implements('search') as $name) {
$items['search/' . $name . '/%menu_tail']['page callback'] = 'test_search_view';
}
}
// Note: identical to search_view except for --- CHANGED ---
function test_search_view($type = 'node') {
// Search form submits with POST but redirects to GET. This way we can keep
// the search query URL clean as a whistle:
// search/type/keyword+keyword
if (!isset($_POST['form_id'])) {
if ($type == '') {
// Note: search/node can not be a default tab because it would take on the
// path of its parent (search). It would prevent remembering keywords when
// switching tabs. This is why we drupal_goto to it from the parent instead.
drupal_goto('search/node');
}
$keys = search_get_keys();
// Only perform search if there is non-whitespace search term:
$results = '';
if (trim($keys)) {
// Log the search keys:
watchdog('search', '%keys (#type).', array('%keys' => $keys, '#type' => module_invoke($type, 'search', 'name')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));
// Collect the search results:
// --- CHANGED ---
// $results = search_data($keys, $type);
// Instead of using search_data, use our own function
$results = test_search_data($keys, $type);
// --- END CHANGED ---
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), search_help('search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('search_form', NULL, $keys, $type);
$output .= $results;
return $output;
}
return drupal_get_form('search_form', NULL, empty($keys) ? '' : $keys, $type);
}
// Note: identical to search_data() except for --- CHANGED ---
function test_search_data($keys = NULL, $type = 'node') {
if (isset($keys)) {
if (module_hook($type, 'search')) {
$results = module_invoke($type, 'search', 'search', $keys);
if (isset($results) && is_array($results) && count($results)) {
// --- CHANGED ---
// This dsm() is called immediately after hook_search() but before
// the results get themed. Put your code here.
dsm($results);
// --- END CHANGED ---
if (module_hook($type, 'search_page')) {
return module_invoke($type, 'search_page', $results);
}
else {
return theme('search_results', $results, $type);
}
}
}
}
}
You can use hook_search_page() to reorder or format the search result.
Hook search_execute allows you to modify the query in the way you needed. You can even fire new queries with custom sql, for example:
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
// Do some query here.
$result = my_fancy_query();
// Results in a Drupal themed way for search.
$results[] = array(
'link' => (string) $result->U,
'title' => $title,
'snippet' => $snippet,
'keys' => check_plain($keys),
'extra' => array($extra),
'date' => NULL,
);