Just another WordPress.com site

Archive for the ‘Uncategorized’ Category

Worpress Code snippets, Like excerpt, featured image

  1. By Default WordPress displays the excerpt of the current post with the “[…]” text at the end, which is not a “read more” link. So to have a custom excerpt add following to the function.php

function new_excerpt_more($more) {
global $post;
return ‘<p><a href=”‘ . get_permalink($post->ID) . ‘”> Continue Reading</a></p>’;
}
add_filter(‘excerpt_more’, ‘new_excerpt_more’);

  1. To Enable Featured Image
  2. To Avoid Google Ranking please find detailed article at ecarobar.com
Advertisements

wp_localize_script: Passing parameters from PHP to Javascripts in plugins

A while back, I wrote a post detailing why it was a bad idea to generate Javascripts using PHP in WordPress plugins. In that post, I mentioned a couple of better ways to do it.

At the time, I didn’t know about the third, and best way, to accomplish this. Mike’s comment over there reminded me of it. WordPress has it built in.

If you already know about wp_localize_script, you can stop reading now.

The wp_localize_script function was made in order to allow for WordPress translations to be able to also translate some of the JS files inside WordPress. Thus the name “localize”. The way it works is to load up the translated versions of text from the translation files and then include them into the resulting HTML output as a Javascript object. The scripts then use that object to produce any text output they need to produce.

Turns out that’s really similar to our goal of sending arbitrary parameters from WordPress to be used by Javascript code.

How to do it:

1. Make your script static (instead of generated) and enqueue your script as per normal. Example:

1

wp_enqueue_script(\’my-script\’,\’/path/to/whatever.js\’,…);

No real changes there. You’ll have to come back and modify your script to use these parameters it’s getting passed, but we’ll get to that in a minute.

2. Build an array of your parameters that you want to send to the script.

1

2

3

4

$params = array(

  \’foo\’ => \’bar\’,

  \’setting\’ => 123,

);

Note that my parameters are simple examples, but this is PHP code. You can get your parameters however you like. Such as get_option to pull them from the database, perhaps.

3. Call wp_localize_script and give your parameters a unique name.

1

wp_localize_script( \’my-script\’, \’MyScriptParams\’, $params );

What this will do is make WordPress output an inline script with your parameters (properly encoded) just before the enqueue outputs the script tag that loads your script in the first place. So then those parameters will be available to your script as an instance of an object with “MyScriptParams” (from my example).

This means that Javascript code can now reference them as attributes of the name you gave.

So, step 4. Modify your script to use those parameters. In my example, I used “MyScriptParams” and the parameter names are “foo” and “setting”. In my Javascript code I can use them as “MyScriptParams.foo” and “MyScriptParams.setting”.

Much cleaner. One static and unchanging JS file to cache. Parameters get put into your HTML itself as a one-liner. You can deal with the parameters using a normal PHP array before passing them over. No need to screw around with generating Javascript from PHP or looking for wp-load or even messing with tricky actions.

Perfect.

via wp_localize_script » Otto on WordPress.

User-editable text metadata | Pydio, formerly AjaXplorer

A common need for a system like AjaXplorer is to let the users enter their own comments or remarks about the files they use. AjaXplorer lets you simply define as much metadata fields as you want, with various field types available, through this plugin meta.user.

This plugin requires a « metastore » plugin to be active to do the actual storing implementation. If you are not sure of what this mean, just read the previous section. Metastore will handle the actual storing of the metadata, where as the plugin will handle how it is displayed and other users interface.

Metadata is attached to a file, which means it is moved/copied/deleted between folders when such operations are applied on the files. The plugin provides a little editor for adding/modifying these properties as simple text lines, display them in both the file list and in the infoPanel, and the added metadata is also searchable.

To add some metadata fields, simply follow the steps :

In the « Repository Features » of a workspace configuration panel, make sure a MetaStore is defined, and add a « Text Metadata » plugin to the stack.

You can see a replicable set of three fiels :

Meta Field: a technical name for the field. Please use only alphanumerical characters. See below for specific keywords.

Meta Label: will be displayed to the user

Column visibility: can be « visible » or « hidden » (without quotes). This defines whether in List mode, the associated will be visible by default or not.

Some special keywords can be used to name metadata fields, that will behave specially in terms of GUI :

stars_rate : the field automatically turns into a 5-stars rating system for the files. View and edit the rating directly in the InfoPanel, in the FilesList (in list mode only for the moment), and in the « File Meta Data » form.

css_label : the field turns into a labeling system that will apply a given css class to either the table row when in list mode, or the thumbnail cell when in thumb mode. The css classes are defined in plugins/meta.serial/css and by default they define 5 levels of priority with associated background colors. Use png transparent images as background colors, that way the user can still notice when a row is selected or not.

area_XXX : Prepending « area_ » to a field name will create a textarea field.

For example, here is below a correspondance between a set of configuration and the result for the end user :

 

via User-editable text metadata | Pydio, formerly AjaXplorer.

Metastore, meta & index plugins | Pydio, formerly AjaXplorer

As explained in the previous chapter, a workspace is mainly configured by 1/ its access driver (how do I access the actual data?) and 2/ additional plugins (enriching the data & features). This second part is handled by various plugins that are all of a specific type : metastore, meta,  and index. This order is not a random one : when adding a plugin you will notice that AjaXplorer will always reorder them like that. All these aspects will generally handle not the « data » itself (your files, their content), but « metadata », that is additionnal data describing the files. This data can be inherent to the files (e.g., the filesize can actually be seen as a metadata), or external, generated by the users (user-defined metadata) or by any system (a revision number from a versioning system).

So to take them in the order :

Metastore:

Defines how the metadata will be stored for the current workspace.  This can be linked to the underlying access driver but not necessarily.

Always the first in the stack, as meta & index plugins will often actually depend on a metastore.  Other features (like sharing and bookmarks) makes use of this feature to provide a better user experience as well. It it thus always recommanded to add at least a metastore to each workspace.

Current implementations include metastore.serial (stores files metadata on local filesystem, inside hidden files), metastore.s3 (to be used with access.s3, uses Amazon metadata capabilities) and metastore.xattr (uses file system Extended attributes, still experimental).

Generally if you are not sure, metastore.serial will do the job.

Meta:

One or many meta plugins can be added, they will actually implement the real features, and generally will require a metastore to be present for storing/retrieving their custom metadata.

Can go from user-defined metadata to quota implementation or versionning. See following sections of this manual.

Index

Indexation plugins, only Lucene is currently bundled by default, should be sufficient.

Always appears at the end of the stack, as other plugins can register metadata to be indexed by the search engine.

In the next sections, we will go through the common features one wants to implement on the workspaces. Please check the plugins documentations for detailed instruction and additional available features.

via Metastore, meta & index plugins | Pydio, formerly AjaXplorer.

WordPress WordPress : Queries for moving from dev to live

UPDATE wp_posts SET guid = replace(guid, 'http://www.old-domain.com','http://www.new-domain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.old-domain.com', 'http://www.new-domain.com');

WordPress Plugins

.main-inner .widget .post-body ul{ list-style: decimal; } .main-inner .widget .post-body ul li ul{ list-style: lower-roman outside none; }
Some Important WordPress plugin:

  • User Management

    • User Access Manager
    • Capability Manager Enhanced
    • Role Scoper (best combination to use with Capability Manager Enhanced)
  • Excerpt

    • Advanced Excerpt
  • Security

    • Better WP Security
    • Really Simple CAPTCHA
  • PDF

    • BSK PDF Manager
    • Print Friendly and PDF
  • Custom Post

  • Forms

  • Site Down/Maintenance

    • Maintenance Mode
  • Cross Platform/Cross CMS

    • Joomla/Mambo to WP Migrator
  • Social Media

    • Recent Tweets Widget
  • Slider/Carousel/Lightbox

First WordPress plugin

First WordPress plugin

/* Plugin Name: crud operation
 * Plugin URI: http://www.datum.com
 * description: a plugin for performing basic crud operations
 * Vesion: 1.0
 * Author URI: http://www.datum.com
 * license: GP2
 */
function crud_setUserCaps($param) {
    $editor = get_role(strtolower($param));
    $editor->add_cap(‘edit_download_item’);
    $editor->add_cap(‘read_download_item’);
    $editor->add_cap(‘delete_download_item’);
    $editor->add_cap(‘edit_download_items’);
    $editor->add_cap(‘delete_download_items’);
    $editor->add_cap(‘read_download_items’);
}
function crud_unsetUserCaps($param) {
    $editor = get_role(strtolower($param));
    $editor->remove_cap(‘edit_download_item’);
    $editor->remove_cap(‘read_download_item’);
    $editor->remove_cap(‘delete_download_item’);
    $editor->remove_cap(‘edit_download_items’);
    $editor->remove_cap(‘delete_download_items’);
    $editor->remove_cap(‘read_download_items’);
}
function set_caps() {
    //author,subscriber,contributor
    crud_setUserCaps(‘editor’);
    crud_setUserCaps(‘administrator’);
}
function crud_activationFun($param) {
    set_caps();
    crud_createDBTable();
    crud_installData();
    // Then flush them
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, ‘crud_activationFun’);
function crud_deactivationFun($param) {
    crud_dropTable();
    crud_unsetUserCaps(‘editor’);
    crud_unsetUserCaps(‘administrator’);
    flush_rewrite_rules();
}
register_deactivation_hook(__FILE__, ‘crud_deactivation_fun’);
add_action(‘wp_enqueue_scripts’, ‘crud_loadScripts’);
function crud_loadScripts($param) {
    wp_enqueue_script(‘jquery’);
    wp_register_script(‘docready’, plugins_url(‘js/docready.js’, __FILE__));
    wp_enqueue_script(‘docready’);
}
add_action(‘wp_enques_styles’, ‘crud_loadStyles’);
function crud_loadStyles($param) {
    wp_register_style(‘baseStyle’, plugins_url(‘css/style.css’, __FILE__));
    wp_enqueue_style(‘baseStyle’);
}
add_action(‘init’, ‘crud_addRewriteRules’);
function crud_addRewriteRules() {
    add_rewrite_rule(“download_items/^([^/]*)/?”, ‘index.php?post_type=download_items=$matches[1]’, ‘top’);
}
add_action(‘init’, ‘crud_registerDownloadItems’);
function crud_registerDownloadItems() {
    $labels = array(
        ‘menu_name’ => _x(‘download_items’, ‘Download Items’),
        ‘name’ => ‘Download Items’,
        ‘singular_name’ => ‘Download Item’,
        ‘add_new’ => ‘Add New’,
        ‘add_new_item’ => ‘Add New Download Item’,
        ‘edit_item’ => ‘Edit Download Item’,
        ‘new_item’ => ‘New Download Item’,
        ‘all_items’ => ‘All Download Items’,
        ‘view_item’ => ‘View Download Item’,
        ‘search_items’ => ‘Search Download Items’,
        ‘not_found’ => ‘No Download Items found’,
        ‘not_found_in_trash’ => ‘No Download Items found in Trash’,
        ‘parent_item_colon’ => ”,
        ‘menu_name’ => ‘Download Items’
    );
    $args = array(
        ‘labels’ => $labels,
        ‘hierarchical’ => true,
        ‘description’ => ‘Slideshows’,
        ‘supports’ => array(‘title’, ‘editor’),
        ‘public’ => true,
        ‘show_ui’ => true,
        ‘show_in_menu’ => true,
        ‘show_in_nav_menus’ => true,
        ‘publicly_queryable’ => true,
        ‘exclude_from_search’ => false,
        ‘has_archive’ => true,
        ‘query_var’ => true,
        ‘can_export’ => true,
        ‘rewrite’ => array(
            ‘slug’ => ‘download_items’,
            ‘with_front’ => false,
            ‘feed’ => true,
            ‘pages’ => true
        ),
        ‘capabilities’ => array(
            // Meta capabilities
            ‘edit_post’ => ‘edit_download_item’,
            ‘read_post’ => ‘read_download_item’,
            ‘delete_post’ => ‘delete_download_item’,
            // Primitive capabilities
            ‘edit_posts’ => ‘edit_download_items’,
            ‘delete_post’ => ‘delete_download_items’,
            ‘read_posts’ => ‘read_download_items’,
        ),
        ‘capability_type’ => ‘post’
    );
    register_post_type(‘download_items’, $args);
}

add_action(‘add_meta_boxes’, ‘crud_addMetaBoxes’);
function crud_addMetaBoxes() {
    //add_meta_box($id, $title, $callback, $page, $context, $priority);
    add_meta_box(“crud_custom_fields”, “Other Information”, ‘crud_viewFields’, “download_items”, “normal”);
}
function crud_viewFields() {
    global $post, $wpdb;
    $table_name = $wpdb->prefix . “categories”;
    $checked_status = ”;
    $download_price = get_post_meta($post->ID, ‘download_price’);
    $crud_category = get_post_meta($post->ID, ‘crud_category’);
    $myrows = $wpdb->get_results( “SELECT category_name, category_Label FROM {$table_name}” );
   
    $html = ”;
    $html .= ‘

‘;
    $html .= ”

               

               

             

             

               

               

             

           

Download price
Categories “;
    $html .= ‘

    ‘;
       
        foreach ($myrows as $key => $value) {
            if (stristr($crud_category[0], $value->category_name) == true) {
                $checked_status = ‘ checked=”checked” ‘;
                $html .= ‘

  •                     ‘ . $value->category_Label . ‘
                   
  • ‘;
            } else {
                $html .= ‘

  •                     ‘ . $value->category_Label . ‘
                   
  • ‘;
            }
        }

        $html .= “

“;
    echo $html;
}
/* Save Slider Options to database */
add_action(‘save_post’, ‘crud_saveDownloadInfo’);
function crud_saveDownloadInfo($post_id) {

    // verify nonce
    if (!wp_verify_nonce($_POST[‘crud_custom_fields_nonce’], basename(__FILE__))) {
        return $post_id;
    }
    // check autosave
    if (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE) {
        return $post_id;
    }
    // check permissions
    if (‘download_items’ == $_POST[‘post_type’] && current_user_can(‘edit_download_items’, $post_id)) {
        $download_price = (isset($_POST[‘crud_download_price’]) ? $_POST[‘crud_download_price’] : ”);
        $categories = (isset($_POST[‘crud_category’]) ? $_POST[‘crud_category’] : ”);
        $categories = strip_tags(json_encode($categories));
        update_post_meta($post_id, “download_price”, $download_price);
        update_post_meta($post_id, “crud_category”, $categories);
    } else {
        return $post_id;
    }
}
// Callback function to show fields in meta box
add_filter(‘map_meta_cap’, ‘crud_downloadItemMetaCap’, 10, 4);
function crud_downloadItemMetaCap($primitive_caps, $meta_cap, $user_id, $args) {
    // If meta-capability is not download_item based do nothing.
    if (!in_array($meta_cap, array(‘edit_download_item’, ‘delete_download_item’, ‘read_download_item’))) {
        return $primitive_caps;
    }
    // Check post is of post type.
    $post = get_post($args[0]);
    $post_type = get_post_type_object($post->post_type);
    if (‘download_items’ != $post_type) {
        return $primitive_caps;
    }
    $primitive_caps = array();
    switch ($meta_cap):
        case ‘edit_download_item’:
            if ($post->post_author == $user_id) {
                // User is post author
                if (‘publish’ == $post->post_status) {
                    // download_item is published: require ‘edit_published_download_items’ capability
                    $primitive_caps[] = $post_type->cap->edit_published_posts;
                } elseif (‘trash’ == $post->post_status) {
                    if (‘publish’ == get_post_meta($post->ID, ‘_wp_trash_meta_status’, true)) {
                        // download_item is a trashed published post require ‘edit_published_download_items’ capability
                        $primitive_caps[] = $post_type->cap->edit_published_posts;
                    }
                } else {
                    $primitive_caps[] = $post_type->cap->edit_posts;
                }
            } else {
                // The user is trying to edit a post belonging to someone else.
                $primitive_caps[] = $post_type->cap->edit_others_posts;
                // If the post is published or private, extra caps are required.
                if (‘publish’ == $post->post_status) {
                    $primitive_caps[] = $post_type->cap->edit_published_posts;
                } elseif (‘private’ == $post->post_status) {
                    $primitive_caps[] = $post_type->cap->edit_private_posts;
                }
            }
            break;
        case ‘read_download_item’:
            if (‘private’ != $post->post_status) {
                // If the post is not private, just require read capability
                $primitive_caps[] = $post_type->cap->read;
            } elseif ($post->post_author == $user_id) {
                // Post is private, but current user is author
                $primitive_caps[] = $post_type->cap->read;
            } else {
                // Post is private, and current user is not the author
                $primitive_caps[] = $post_type->cap->read_private_post;
            }
            break;
        case ‘delete_download_item’:
            if ($post->post_author == $user_id) {
                // Current user is author, require delete_download_items capability
                $primitive_caps[] = $post_type->cap->delete_posts;
            } else {
                // Current user is no the author, require delete_others_download_items capability
                $primitive_caps[] = $post_type->cap->delete_others_posts;
            }
            // If post is published, require delete_published_posts capability too
            if (‘publish’ == $post->post_status) {
                $primitive_caps[] = $post_type->cap->delete_published_posts;
            }
            break;
    endswitch;
    return $primitive_caps;
}
function crud_frontendDeleteLink() {
    if (!current_user_can(‘delete_download_items’)) {
        echo ‘    ‘;
        return;
    }
    $url = add_query_arg(
            array(
                ‘action’ => ‘frontend_delete’,
                ‘post’ => get_the_ID()
            )
    );
    echo “Delete“;
}
if (isset($_REQUEST[‘action’]) && $_REQUEST[‘action’] == ‘frontend_delete’) {
    add_action(‘init’, ‘crud_FrontendDeletePost’);
}
function crud_FrontendDeletePost() {
    if (!current_user_can(‘delete_download_items’))
        return;
    $post_id = (isset($_REQUEST[‘post’]) ? (int) $_REQUEST[‘post’] : 0);
    if (empty($post_id))
        return;
    wp_trash_post($post_id);
}
add_shortcode(‘downloadItem’, crud_downloadItemFun);
function crud_downloadItemFun() {
    set_caps();
    global $post ;
   $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
    $args = array(
      ‘posts_per_page’ => 10,
      ‘post_type’ => ‘download_items’,
      ‘paged’ => $paged
    );
    $newsObj = new WP_Query($args);
    if ($newsObj->have_posts()):    ?>
       

           

               

               

               

               

               

           

           
                while ($newsObj->have_posts()): $newsObj->the_post();
        $curr_id = get_the_ID();
        $meta = get_post_meta( $curr_id,’crud_category’ );
        $meta = preg_replace(‘/[^a-zA-Z0-9\,]/’, ”, $meta);
        $download_price = get_post_meta( $curr_id,’download_price’ );
        ?>
           

               

               

               

               

               

           

                endwhile;?>
       

Title Categories Price Edit Delete
0 ) {echo $meta[0] ;} ?> 0 ) echo implode(‘,’, $download_price); ?> “>Edit

            endif;
    wp_reset_query();
}
add_action(‘admin_menu’,’crud_pluginSetting’);
function crud_pluginSetting() {
    add_menu_page(‘Crud Plugin Settings’, ‘Crud Settings’, ‘administrator’, ‘crud_settings’, ‘crud_settingFunction’);
}
if (isset($_REQUEST[‘category_label’]) && (!empty ($_REQUEST[‘category_label’]) || ” != ‘frontend_delete’)) {
    crud_installData($_REQUEST[‘category_name’], $_REQUEST[‘category_label’]);
}
function crud_settingFunction() {
    $category_label = (get_option(‘category_label’) != ”) ? get_option(‘category_label’) : ‘category_label100’;
    $category_name = (get_option(‘category_name’) != ”) ? get_option(‘category_name’) : ‘category_name100’;
    $html = ‘

       

       

Select Your Settings

        ‘ . wp_nonce_field(‘update-options’) . ‘
           

           

               

                   

               

               

                   

               

           

           

                        Category Label
                   
                        Category Name
                   

           
 

           

';
    echo $html;
}
function crud_createDBTable() {
    global $wpdb;
    $table_name = $wpdb->prefix . "categories";
    $sql = "CREATE TABLE $table_name (
  id mediumint(9) NOT NULL AUTO_INCREMENT,
  category_name text NOT NULL,
  category_label text NOT NULL,
  UNIQUE KEY id (id)
    );";
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta($sql);
}
function crud_dropTable() {
    global $wpdb;
    $table_name = $wpdb->prefix . "categories";
    $sql = "DROP TABLE $table_name";
}
function crud_installData($category_name = "News",$category_Label = "News") {
   global $wpdb;
   $table_name = $wpdb->prefix . "categories";
   //$category_name = "News";
   //$category_Label = "News";
   $rows_affected = $wpdb->insert( $table_name, array( 'category_name' => $category_name, 'category_Label' => $category_Label) );
}
//Debug Errors if there are any
add_action('activated_plugin','save_error');
function save_error(){
    file_put_contents(ABSPATH. 'wp-content/uploads/2013/error_activation.html', ob_get_contents());
}
?>
%d bloggers like this: