EzDevInfo.com

wordpress-plugin interview questions

Top wordpress-plugin frequently asked interview questions

How do you add a WordPress admin page without adding it to the menu?

I'm building a WordPress plugin and I'd like to have an edit-item page that can't be reached via the submenu (because then the item wouldn't be specified).

This resource (http://codex.wordpress.org/Adding_Administration_Menus) shows how to associate an admin page with a function, but not how to do so without adding it as a menu item.

Can this be done?

Thanks!


Source: (StackOverflow)

Can I install/update WordPress plugins without providing FTP access?

I am using WordPress on my live server which only uses SFTP using an SSH key.

I want to install and upgrade plugins, but it appears that you are required to enter your FTP login to install the plugins. Is there a way to install and upgrade plugins by manually uploading the files instead of having WordPress handle the entire process?


Source: (StackOverflow)

Advertisements

How to filter WooCommerce products by custom attribute

I'm trying to filter WooCommerce product archive by custom attributes.

For example, there are 5 products with attribute "color" containing "red", and another 3 with attribute "color" containing "blue".

How can I apply a filter to the products loop, so only the products containing "red" will be shown?

Thanks


Source: (StackOverflow)

Woocommerce add to cart button redirect to checkout

I created an ecommerce using the plugin woocommerce. I am selling only a subscription so the "/cart/" page is useless. I'm trying to get rid of it so that when my customer click on "Add to cart" button, he ends up on the checkout page.


Source: (StackOverflow)

Modifying a function to return username correctly, for a wordpress plugin

I have two Wordpress Plugins and both authors of the plugins refuse to admit the clash/issue is their site but it's quite clear that both parties can fix the issue very easily.

I provided one plugin author with the fix that has no negative impact on their plugin in any way, it doesn't cause any problems if the person has the second plugin installed or not but they won't add the fix to their plugin even though it adds compatibility with a different plugin.

I am unable to work out how to fix the second plugin, but I know what needs to be done...

Snippet from Plugin 1 (One that I provided a fix to)

/* check if the user is valid */
if ( true === wlm_admin_in_admin() || true === $special_bypass ) {
    $validuser = username_exists( $data['username'] );

    if ( ! $validuser ) {
        $validuser        = email_exists( $data['email'] );
        $user_info        = get_userdata( $validuser );
        $data['username'] = $user_info->user_login;
    }

    $data['password'] = __( 'Already assigned', 'wishlist-member' );
} else {
    $validuser = wp_login( $data['username'], $data['password'] );
}
if ( $validuser ) {
    $user      = $this->Get_UserData( 0, $data['username'] );
    /* check for blacklist status */
    $blacklist = $this->CheckBlackList( $user->user_email );
}

Now, if find the line:

$validuser = wp_login( $data['username'], $data['password'] );

And replace it with:

//$validuser = wp_login( $data['username'], $data['password'] );
$tmpvaliduser = username_exists( $data['username'] );
if ($tmpvaliduser)
    $validuser = wp_login( $data['username'], $data['password'] );

if ( ! $validuser || !$tmpvaliduser) {     
    if((!$data['email'])  && !(false === strrpos($data['username'], "@")) ) {
        $validuser        = email_exists( $data['username'] );
        $user_info        = get_userdata( $validuser );
        $data['username'] = $user_info->user_login;
        $validuser = wp_login( $data['username'], $data['password'] );  
    }     
}

Then this fixes the issue because it changes the $data['username'] variable to their actual username which means the rest of the plugin 1 will continue correctly and bind certain details to the username (account) rather than a username consisting of their email (which obviously doesn't exist as a username)

  • If username exists (they tried to login with username & password) then it continues like normal.
  • If username does NOT exist then it checks if the email exists instead, if it does then it will grab the username from the email address that was entered and simply changes the entered username field with their actual username instead of their email and then continues like normal

Snippet from Plugin 2 (One that I need a fix for)

function email_login_authenticate( $user, $username, $password ) {
    if ( is_a( $user, 'WP_User' ) )
        return $user;
    if ( !empty( $username ) ) {
        $user = get_user_by( 'email', $username );
        if ( isset( $user, $user->user_login, $user->user_status ) && 0 == (int) $user->user_status ) {
            $username = $user->user_login;
        }
        $result = wp_authenticate_username_password( null, $username, $password );
        if (is_a ( $result, 'WP_User' ) ) {
            global $WishListMemberInstance;
            $WishListMemberInstance->WPMAutoLogin($user->ID);
            $_POST['log'] = $username;
            $WishListMemberInstance->Login();
        }
    }
    return wp_authenticate_username_password( null, $username, $password );
}

I'm not 100% sure what the above snippit does in full, but I understand it good enough and I need to change it so that it returns the correct username somehow so that $data['username'] is replaced with the username instead of the email (if an email is used)


Source: (StackOverflow)

How to check if currently in Wordpress Admin?

I am creating my first plugin and have a single function that controls the output. This function has different output based on whether or not it is being viewed from within the WordPress admin vs. the frontend. Is there any way to easily test whether or not my function is being triggered from within admin vs the frontend?

I've tried conditionally checking the query string against the name of my plugin "page" name but it seems to fail on some servers/installs.

Thanks


Source: (StackOverflow)

How To Include CSS and jQuery in my wordpress plugin?

How To Include CSS and jQuery in my wordpress plugin ?


Source: (StackOverflow)

PHP fopen() Error: failed to open stream: Permission denied

I learning how to write a WordPress plugin. I need some help writing some data to an XML file. I'm on my local machine, a Mac running MAMP. I have PHP 5.2.13. In my plugin, I've got:

$file_handle = fopen('markers.xml', 'w');
$stringdata = "Test Info";
fwrite($file_handle, $stringdata);
fclose($file_handle);

Running the above gives me the following error:

Warning: fopen(markers.xml) [function.fopen]: failed to open stream: Permission denied in /Users/my_name/Sites/my_site/wp-content/plugins/my_plugin_folder/my_plugin_main_file.php on line 73

Warning: fwrite(): supplied argument is not a valid stream resource in /Users/my_name/Sites/my_site/wp-content/plugins/my_plugin_folder/my_plugin_main_file.php on line 75

Warning: fclose(): supplied argument is not a valid stream resource in /Users/my_name/Sites/my_site/wp-content/plugins/my_plugin_folder/my_plugin_main_file.php on line 76

I tried using the absolute path in the $file_handle line: http://my_site/wp-content/plugins/my_plugin_folder/markers.xml. But, that didn't work.

I also tried changing the permissions on markers.xml as follows:

(Me): Read & Write (unknown): Read only everyone: Read & Write

For some reason, my Mac wouldn't let me change (unknown) to Read & Write. I'm not sure if that makes a difference. I right-clicked on the file and selected 'Get Info' in order to change the permissions.

In phpInfo(), I've got:

"Registered PHP Streams https, ftps, compress.zlib, compress.bzip2, php, file, data, http, ftp"

Is a WordPress setting causing the problem? or is it just PHP issue?

Any suggestions on how to solve this problem?

Thank you.


Source: (StackOverflow)

Export User Info into CSV - Additional Column

I'm using the 'Export Users to CSV' a plugin for wordpress. By default, The plugin only extracts wp_users and wp_usermeta

I have been wanting to add post_title column from wp_posts. I was able to pull out the 'post_title' into the CSV file BUT it's not placed correctly in its respective row.

Please see my edited code and original code

Orignal version:

global $wpdb;
$data_keys = array(
    'ID', 'user_login', 'user_pass',
    'user_nicename', 'user_email', 'user_url',
    'user_registered', 'user_activation_key', 'user_status',
    'display_name'
);
$meta_keys = $wpdb->get_results( "SELECT distinct(meta_key) FROM $wpdb->usermeta" );
$meta_keys = wp_list_pluck( $meta_keys, 'meta_key' );
$fields = array_merge( $data_keys, $meta_keys);

$headers = array();
foreach ( $fields as $key => $field ) {
    if ( in_array( $field, $exclude_data ) )
        unset( $fields[$key] );
    else
        $headers[] = '"' . strtolower( $field ) . '"';
}
echo implode( ',', $headers ) . "\n";

foreach ( $users as $user ) {
    $data = array();
    foreach ( $fields as $field ) {
        $value = isset( $user->{$field} ) ? $user->{$field} : '';
        $value = is_array( $value ) ? serialize( $value ) : $value;
        $data[] = '"' . str_replace( '"', '""', $value ) . '"';
    }
    echo implode( ',', $data ) . "\n";
}

Edited version

global $wpdb;

$data_keys = array(
    'ID', 'user_login', 'user_pass',
    'user_nicename', 'user_email', 'user_url',
    'user_registered', 'user_activation_key', 'user_status',
    'display_name'
);
$meta_keys = $wpdb->get_results( "SELECT distinct(meta_key) FROM $wpdb->usermeta" );
$meta_keys = wp_list_pluck( $meta_keys, 'meta_key' );
$post_keys = $wpdb->get_results( "SELECT distinct(post_title) FROM $wpdb->posts" );
$post_keys = wp_list_pluck( $post_keys, 'post_title' );
$fields = array_merge( $data_keys, $meta_keys, $post_keys);

$headers = array();
foreach ( $fields as $key => $field ) {
    if ( in_array( $field, $exclude_data ) )
        unset( $fields[$key] );
    else
        $headers[] = '"' . strtolower( $field ) . '"';
}
echo implode( ',', $headers ) . "\n";

foreach ( $users as $user ) {
    $data = array();
    foreach ( $fields as $field ) {
        $value = isset( $user->{$field} ) ? $user->{$field} : '';
        $value = is_array( $value ) ? serialize( $value ) : $value;
        $data[] = '"' . str_replace( '"', '""', $value ) . '"';
    }
    echo implode( ',', $data ) . "\n";
}

I hope my explanation is not confusing. Cheers!

Here's an image to explain it better :

https://www.dropbox.com/s/xijkb4fp16atcx3/question-jpeg.jpg?dl=0


Source: (StackOverflow)

Wordpress Plugin: Call function on button click in admin panel

I need to create a wordpress plug-in that calls a php function when a button in a admin panel is clicked. I've been looking at tutorials for writing basic wordpress plugins and adding admin panels but I still don't understand how exactly to register a button to a specific function in my plug-in.

Help me out with some examples or good resources plz

Here's what I have so far

/*
Plugin Name: 
Plugin URI: 
Description: 
Author:
Version: 1.0
Author URI:
*/


add_action('admin_menu', 'wc_plugin_menu');

function wc_plugin_menu(){
 add_management_page('Title', 'MenuTitle', 'manage_options', 'wc-admin-menu', 'wc_plugin_options'); 

}

function wc_plugin_options(){
if (!current_user_can('manage_options'))  {
    wp_die( __('You do not have sufficient permissions to access this page.')    );
}
echo '<div class="wrap">';
echo '<button>Call Function!</button>'; //add some type of hook to call function
echo '</div>';

}

function button_function()
{
//do some stuff
} 


?>

Source: (StackOverflow)

WordPress plugin development using OOP

I am new to plugin development. So please correct me, wherever I get it wrong.

I have a website which needs a players plugin with the following needs:-

  • An administrator controllable form for player registration, with some details of them.
  • A listing page where all the registered players are to be shown.
  • Registered players can be deleted & compared with each other.
  • Showing some registered players (10 random players) in the WordPress theme in the front-end.

I have completed the activation of the plugin, along with database table creation and administrator menu options for this plugin. I have also completed the player registration interface, but without the database insertion code. But all of these have been done using normal procedural way.

I now have two headaches in completing the development of this plugin:-

  • Develop this plugin in the OOP format, for support to future versions of WordPress.
  • Complete the other requirements of this plugin.

How to proceed with the following (even with a little knowledge sharing)?

  • Creating a WordPress plugin from scratch using the OOP way.
  • Calling a web form (like, for player registration) using OOP.
  • Submitting all these player information into the database using OOP.
  • Showing a listing page (like, for registered players and positioning them) using OOP.
  • Showing some players in the front-end of the WordPress theme, using either Template Tags or directly with the help of the plugin.

I have searched Google, tried to find some information in the Internet about these, but I haven't succeeded much with the OOP thing.

EDIT:- It will be very helpful and nice for all of us (new to WordPress OOP plugin development) to have some code snippet highlighting its use. If possible, you can also provide some article links which will properly describe how to write such OOP plugins.

Articles, like what "gulbrandr" provided, was helpful, and I also would like to thank "kovshenin" for sharing / mentioning links of some OOP plugins; but it will be very great if some more articles or any code snippet can be provided, describing the proper steps of developing the OOP plugins.


Source: (StackOverflow)

WordPress, jQuery UI CSS Files?

I'm trying to create a WordPress plugin, and I would like to have jQuery UI Tabs in one of my settings pages.

I already have the scripting code set:

wp_enqueue_script('jquery');                    // Enque jQuery
wp_enqueue_script('jquery-ui-core');            // Enque jQuery UI Core
wp_enqueue_script('jquery-ui-tabs');            // Enque jQuery UI Tabs

...and I have created the HTML and JavaScript too. Until here all are fine.

The question is:

The WordPress platform comes with some scripts already pre-installed like the one I have enqueue above. My script runs fine with the tabs, but it is not styled! So what I'm trying to ask, does the WordPress platform come with jQuery UI Theme pre-installed? ...and if so, how do I enqueue the style into my plugin?


Source: (StackOverflow)

WordPress + Multisite: How to add custom blog options to Add New Site form in Network Admin?

In a WordPress Multisite installation I'm customizing, I need to add a simple text field to the entry form for creating new blog sites, which is located at

Network Admin > Sites > Add New

Naturally I need this field to get saved along with the other meta data from that form, in the {new_blog_prefix}_options table.

I'm particularly interested for the simplest, most straightforward, and/or the "right way" (i.e. The WordPress Way) to accomplish this, but I'll settle for The Way That Works™!

So far I've encountered numerous dead-ends in my research:

  • Settings API - [WP Codex]

    As far as I can tell, the Settings API (a) may not work for the Network Admin section (although this may have changed in a recent version of WP); furthermore, (b) it seems like this only lets you add/modify screens in the Settings section of the Dashboard.

  • wpmu_options hook - [Hooks DB]

    Seems to be a hook exclusively for adding options to the Network Settings screen.

  • add_site_option / add_blog_option - [WP Codex]

    Closest I can find; seems to allow adding site-specific options to the {blogsite_prefix}_options table, but still doesn't help with adding options to the Admin form.

So... no dice. Any help is appreciated!


Source: (StackOverflow)

WooCommerce - where can I edit HTML generated by hooks?

I'm new to WooCommerce. Anyhow, I want to create my own theme, so I followed the guidelines and copied accross the core template files to /mywordpresstheme/woocommerce/.

That all works great and I'm editing the templates just fine.

However, the way hooks and actions work in WooCommerce is baffling me and I can't work out where certain parts of generated HTML are coming from.

For example, in content-product.php, there is a hook that gets the image:

<?php
/*
* woocommerce_before_shop_loop_item_title hook
*
* @hooked woocommerce_show_product_loop_sale_flash - 10
* @hooked woocommerce_template_loop_product_thumbnail - 10
*/
do_action( 'woocommerce_before_shop_loop_item_title' );
?>

But what is this? Where does it come from?? Is there any clue in the action name as to where I could locate the HTML being generated for the purpose of editing it?

I've read the article on 'hooks and filters' on WooCommerce, but it explains nothing regarding where or how to change these on a case for case basis.

Any help would be greatly appreciated.

I'm new to this system and I'm sure I'm simply over-looking something very obvious.

Thanks, Mikey.


Source: (StackOverflow)

I want a pagination to my options page of wordpress plugin?

MY DEMO

I want a pagination according to the results coming from wordpress database...This is all done on my options page of wordpress plugin..

My code to retrieve from database is as follows

$per_page=5;
$sql = "SELECT * FROM wp_dive ";
$result = $wpdb->get_results($sql_10) or die(mysql_error());
$length=count($result);
$pages = ceil($length/$per_page);
foreach( $result as $results ) 

    {
    $id=$results->id;
    $name= $results->name_cust;
    $gender= $results->gender_cust;
    $dob= $results->dob_cust;

<?php $html= "<div class=\"divContentBody\">";?>
<?php $html .= "<span class=\"clsOrderNo\">". $id."</span>";?>
<?php $html .= "<span class=\"clsName\">". $name."</span>";?>
<?php $html .= "<span class=\"clsGender\">".$gender."</span>";?>
<?php $html .= "<span class=\"clsDOB\">".  $dob ."</span>";?>
<?php $html .= "</div>"?>
<?php
$data_html .=$html; 
 }

 ?> 

I m getting the data dynamically ..I just want to add pagination ..to show 5 entries on first page and accordingly ...


Source: (StackOverflow)