Wordpress - How do I debug if the right parameters are added to my shortcode? - wordpress

I am trying to debug if parameters are added to my shortcode. Currently, when I add a shortcode to my page and don't add a parameter it errors saying
Updating failed
But I would like to have a more detailed error. How would I do that? I'm working with code snippets and this is a front-end snippet. I noticed that I do get the error when I run the snippet in the back-end but then my entire WP UI disappears which isn't nice. Any tips?
<?php
add_shortcode('taxonomy_dropdown', 'do_taxonomy_dropdown');
function do_taxonomy_dropdown($atts = [])
{
$atts = array_change_key_case((array) $atts, CASE_LOWER);
if(do_validate_parameters($atts)){return;}
$taxonomy = $atts['taxonomy'];
$dependent = $atts['dependent'];
return;
}
function do_validate_parameters($atts = [])
{
$has_parameters = true;
if(!isset($atts['taxonomy'])){
echo "You forgot to add the taxonomy parameter.";
$has_parameters = false;
}
if(!isset($atts['dependent'])){
echo "You forgot to add the dependent parameter.";
$has_parameters = false;
}
return $has_parameters;
}

I think the issue you're having is with the initial portion not checking for the set variable. When I run it with error logging on I see that as an issue. Try this and see if it stops the issue.
add_shortcode('taxonomy_dropdown', 'do_taxonomy_dropdown');
function do_taxonomy_dropdown($atts = [])
{
$atts = array_change_key_case((array) $atts, CASE_LOWER);
if(do_validate_parameters($atts)){return;}
if ( isset($atts['taxonomy'])){
$taxonomy = $atts['taxonomy'];
}
if ( isset($atts['dependent'])){
$dependent = $atts['dependent'];
}
return;
}
function do_validate_parameters($atts = [])
{
$has_parameters = true;
if(!isset($atts['taxonomy'])){
echo "<p>You forgot to add the taxonomy parameter.</p>";
$has_parameters = false;
}
if(!isset($atts['dependent'])){
echo "<p>You forgot to add the dependent parameter.</p>";
$has_parameters = false;
}
return $has_parameters;
}

Related

Override wordpress routing / url rewriting?

I would like to serve different content based on the URL.
I started with a custom page setup via a custom template but I am open to something else.
The main goal is to have one PHP page that can serve different contents programmatically based on the URL.
For example:
https://some-url.com/my-plugin/ -> run my page
https://some-url.com/my-plugin/foo/ -> run my page
https://some-url.com/my-plugin/foo2/abc/ -> run my page
etc...
I have been looking at add_rewrite_rule, add_rewrite_tag, flush_rewrite_rules and WP_Rewrite API but I am getting confused about which one I should use?
I found an example here but I could not make it work, I get 404s, any idea why?:
/*
Plugin Name: Products Plugin
Plugin URI: http://clivern.com/
Description: Register URL rules for our products
Version: 1.0
Author: Clivern
Author URI: http://clivern.com
License: MIT
*/
function products_plugin_activate() {
products_plugin_rules();
flush_rewrite_rules();
}
function products_plugin_deactivate() {
flush_rewrite_rules();
}
function products_plugin_rules() {
add_rewrite_rule('products/?([^/]*)', 'index.php?pagename=products&product_id=$matches[1]', 'top');
}
function products_plugin_query_vars($vars) {
$vars[] = 'product_id';
return $vars;
}
function products_plugin_display() {
$products_page = get_query_var('pagename');
$product_id = get_query_var('product_id');
if ('products' == $products_page && '' == $product_id):
//show all products
exit;
elseif ('products' == $products_page && '' != $product_id):
//show product page
exit;
endif;
}
//register activation function
register_activation_hook(__FILE__, 'products_plugin_activate');
//register deactivation function
register_deactivation_hook(__FILE__, 'products_plugin_deactivate');
//add rewrite rules in case another plugin flushes rules
add_action('init', 'products_plugin_rules');
//add plugin query vars (product_id) to wordpress
add_filter('query_vars', 'products_plugin_query_vars');
//register plugin custom pages display
add_filter('template_redirect', 'products_plugin_display');
First of all, make sure your pretty permalinks are enabled, in this case the option "Plain" in Settings - Permalinks should be unselected:
Select one of these options to enable pretty permalinks
You can check whether pretty permalinks are enabled in the code like so:
function is_enabled_pretty_permalinks() {
return !empty( get_option( 'permalink_structure' ) );
}
if ( is_enabled_pretty_permalinks() ) {
echo 'Pretty permalinks enabled';
}
Next add a new rewrite rule:
function add_my_rewrite_rule() {
$page_slug = 'products'; // slug of the page you want to be shown to
$param = 'do'; // param name you want to handle on the page
add_rewrite_rule('my-plugin/?([^/]*)', 'index.php?pagename=' . $page_slug . '&' . $param . '=$matches[1]', 'top');
}
add_action('init', 'add_my_rewrite_rule');
Add your parameter to query vars so you will be able to handle it on the page:
function add_my_query_vars($vars) {
$vars[] = 'do'; // param name you want to handle on the page
return $vars;
}
add_filter('query_vars', 'add_my_query_vars');
Then you can access your query var do in the page template or in a shortcode, for example:
function my_plugin_shortcode_handler( $atts ){
$do = get_query_var( 'do' );
if ( $do === 'this' ) {
return 'do this';
} else {
return 'do that';
}
}
add_shortcode( 'myshortcode', 'my_plugin_shortcode_handler' );
Then place the shortcode to the content via Gutenberg.
Check out the links:
https://some-url.com/my-plugin/this/ - outputs "do this"
https://some-url.com/my-plugin/that/ - outputs "do that".
This can be solved by using query params. Like you mentioned you have set up custom page via a custom template. You can read the URL and check for the parameters and based on that you can send data from the PHP template page.
e.g,
function cleanTheInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
if (isset($_GET['page_url'])) {
$theUrl = cleanTheInput($_GET['page_url']);
}
if($theUrl == 266)){
// data for https://some-url.com/?page_url=266
}
if($theUrl == 366)){
// data for https://some-url.com/?page_url=366
}

Hook to run after removing a user

I have a function where I duplicate a user to all subsite when they registered.
I achieved that by doing this:
function sync_user( $user_id )
{
$list_ids = get_sites();
$current_site = get_current_site();
$info = get_userdata($user_id);
foreach( $list_ids as $list )
{
if ( $list->blog_id != $current_site->id )
{
add_user_to_blog($list->id, $info->ID, 'subscriber');
}
}
// quick fix for: above somehow doesn't add to main site. add to main site here.
add_user_to_blog(1, $info->ID, 'subscriber');
}
Now, I want to "unsyc" the user when I removed the user from the site. I tried to hook it by using 'remove_user_from_blog', but it caused infinite loop.
Where can I hook the following code so that I can remove all those users that I added previously using above code?
function unsync_user( $user_id )
{
$list_ids = get_sites();
foreach( $list_ids as $list )
{
remove_user_from_blog( $user_id, $list->ID );
}
}
edited the title for clarity
AbdulRahman was correct about that. When user click 'remove' from the user list, the action not fire 'delete_user' or 'deleted_user' hook. I tested it.
I think it is tricky. So, here is how to add custom removed_user action. Add these lines below into your plugin.
add_action('remove_user_from_blog', function($user_id, $blog_id) {
// checking current action
// refer: wp-admin/users.php:99
$wp_list_table = _get_list_table( 'WP_Users_List_Table' );
if( $wp_list_table->current_action() != 'doremove' ) {
return; // only proceed for specific user list action
}
$fire_removed_user_hook = null; // closure reference
$fire_removed_user_hook = function() use ($user_id, $blog_id, &$fire_removed_user_hook) {
do_action( 'removed_user', $user_id, $blog_id );
// remove the hook back
remove_action('switch_blog', $fire_removed_user_hook);
};
// restore_current_blog called at the last line in the remove_user_from_blog function
// so action switch_blog fired
add_action('switch_blog', $fire_removed_user_hook);
}, 10, 2);
add_action('removed_user', function($user_id, $blog_id) {
// the user removed from be blog at this point
}, 10, 2);
The hook "deleted_user" runs after a user is deleted ("delete_user" runs before the deletion occurs):
https://codex.wordpress.org/Plugin_API/Action_Reference/deleted_user

Is that possible to use laravel blade outside the view folder?

I got a wordpress blog inside the public sub folder.
I wanted to use same layout with the laravel view that using blade.
Is there anyway to achieve that?
Yous just need to add your paths to app/config/view.php and blade will automatically find them
You can define a custom namespace for easier usage:
// Register your custom namespace in your AppServiceProvider in the boot() method
view()->addNamespace('custom_views', app_path('custom_path'));
// usage:
view('custom_views::some.view.name')
I managed to do this with the following function:
function bladeCompile ($from, $to, $data)
{
$fs = new \Illuminate\Filesystem\Filesystem;
$b = new \Illuminate\View\Compilers\BladeCompiler($fs, __DIR__);
$src = $b->compileString (file_get_contents($from));
$isPhp = false;
if (substr( $src, 0, 5 ) === "<?php")
{
$isPhp = true;
$src = substr($src, 5);
}
$tempFileName = tempnam("/tmp", "blade-compile");
file_put_contents($tempFileName, $src);
ob_start();
extract($data);
include $tempFileName;
$out = ob_get_clean();
if ($isPhp)
{
$out = '<?php'.$out;
}
file_put_contents($to, $out);
}
And then use with:
$data = array ( // equivalent to the 'with' function.
'parameter' => 'value';
);
bladeCompile ('input.blade.file', 'result.file', $data);

Wordpress Excerpt with allowable tags is not working?

I am trying to create the simple excerpt plugin in Wordpress. I Googled a lot the allowable tag is not working, can anyone give me a suggestion how to do this?
class fpexcerpt {
function __construct() {
require_once('inc/template.php');
if(isset($_POST['reset'])) {
add_action('admin_init',array($this,'fpexcerptrestore'));
}
}
function fpexcerptdefault() {
add_option('fpexcerptcount',55);
add_option('fpexcerptmore','[...]');
}
function fpexcerptrestore() {
delete_option('fpexcerpttag');
delete_option('fpexcerptcount');
delete_option('fpexcerptmore');
fpexcerpt::fpexcerptdefault();
}
function fpexcerptadmin() {
add_submenu_page('options-general.php','Fantastic Excerpt', 'Fantastic Excerpt', 'manage_options','fpexcerptadmin', 'fpexcerptadmin_menu');
}
function fpexcerptupdate() {
register_setting('fpexcpt','fpexcerpttag');
register_setting('fpexcpt','fpexcerptcount');
register_setting('fpexcpt','fpexcerptmore');
}
function improved_trim_excerpt($text) {
global $post;
if ( '' == $text ) {
$text = get_the_excerpt();
$text = apply_filters('the_excerpt',$text);
// $text = str_replace('\]\]\>', ']]>', $text);
$text = strip_tags($text, '<a>');
$excerpt_length = 80;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '[...]');
$text = implode(' ', $words);
}
}
return $text;
}
}
$new = new fpexcerpt();
register_activation_hook(__FILE__,array('fpexcerpt','fpexcerptdefault'));
//remove_all_filters('wp_trim_excerpt');
//add_filter('get_the_excerpt', array('fpexcerpt','fpexcerptprocess'));
remove_filter('get_the_excerpt',array('fpexcerpt','wp_trim_excerpt'));
add_filter('get_the_excerpt', array('fpexcerpt','improved_trim_excerpt'));
add_action('admin_menu',array('fpexcerpt','fpexcerptadmin'));
add_action('admin_init',array('fpexcerpt','fpexcerptupdate'));
?>
EDIT:
The first image is show the excerpt content when i click the particular post its getting link but not in excerpt even if i add the excerpt plugin (mine)
Error: Maximum function nesting level of '100' reached, aborting! in E:\wamp\www\fp\wp-includes\cache.php on line 453
Based on the error you've reported above, I can surmise you're stuck in a recursive function call loop. In other words, a function you've written is ( at some point in the callstack ) calling itself ( or a function that calls it ). Picture an infinite loop, but with functions.
I can't determine where this is occurring since I can't see all of your code.

Wordpress: How to obtain different excerpt lengths depending on a parameter

The length of the excerpt in wordpress is 55 words by default.
I can modify this value with the following code:
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
So, the following call will return just 20 words:
the_excerpt();
But I can't figure out how could I add a parameter to obtain different lengths, so that I could call, for example:
the_excerpt(20);
the_excerpt(34);
Any ideas? Thanks!
uhm, answering me again, the solution was actually quite trivial. it's not possible, as far as i know, to pass a parameter to the function my_excerpt_length() (unless you want to modify the core code of wordpress), but it is possible to use a global variable. so, you can add something like this to your functions.php file:
function my_excerpt_length() {
global $myExcerptLength;
if ($myExcerptLength) {
return $myExcerptLength;
} else {
return 80; //default value
}
}
add_filter('excerpt_length', 'my_excerpt_length');
And then, before calling the excerpt within the loop, you specify a value for $myExcerptLength (don't forget to set it back to 0 if you want to have the default value for the rest of your posts):
<?php
$myExcerptLength=35;
echo get_the_excerpt();
$myExcerptLength=0;
?>
There is no way to do this as far as I have found using the_excerpt().
There is a similar StackOverflow question here.
The only thing I have found to do is write a new function to take the_excerpt()'s place. Put some variation of the code below into functions.php and call limit_content($yourLength) instead of the_excerpt().
function limit_content($content_length = 250, $allowtags = true, $allowedtags = '') {
global $post;
$content = $post->post_content;
$content = apply_filters('the_content', $content);
if (!$allowtags){
$allowedtags .= '<style>';
$content = strip_tags($content, $allowedtags);
}
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) {
array_pop($wordarray);
array_push($wordarray, '...');
$content = implode(' ', $wordarray);
$content .= "</p>";
}
echo $content;
}
(Function credit: fusedthought.com)
There are also "advanced excerpt" plugins that provide functionality like this you can check into.
Thanks for your answer, thaddeusmt.
I am finally implementing the following solution, which offers a different length depending on the category and a counter ($myCounter is a counter within the loop)
/* Custom length for the_excerpt */
function my_excerpt_length($length) {
global $myCounter;
if (is_home()) {
return 80;
} else if(is_archive()) {
if ($myCounter==1) {
return 60;
} else {
return 25;
}
} else {
return 80;
}
}
add_filter('excerpt_length', 'my_excerpt_length');

Resources