GithubHelp home page GithubHelp logo

roborourke / wp-less Goto Github PK

View Code? Open in Web Editor NEW
222.0 222.0 57.0 72 KB

Provides a LESS compiler compatible with wp_enqueue_style() for rapid CSS development in themes and plugins.

License: MIT License

PHP 100.00%

wp-less's Introduction

Alright ๐Ÿ‘‹

Rob's github stats

  • ๐Ÿš€ Working as a principal engineer and lead on Altis DXP at Human Made
  • ๐Ÿ“ˆ Learning about data science (ML anyone?)
  • ๐Ÿง—โ€โ™‚๏ธ Love climbing
  • ๐Ÿ’ฌ Ask me about WordPress, React, Analytics
  • โšก๏ธ Check out my most recent side project buzby.app
  • ๐Ÿ‘จโ€๐Ÿ’ป How I work

wp-less's People

Contributors

bradyvercher avatar franz-josef-kaiser avatar joehoyle avatar justin-lovell avatar maiki avatar rarst avatar richardtape avatar rmccue avatar roborourke avatar scottsweb avatar simonwheatley avatar tomjn avatar vburlak avatar willmot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-less's Issues

Remove PHP4 compatibility

Currently the __construct() has PHP4 references.

Those can be simply removed: &$this becomes $this in PHP5.

PHP 4 needed that to get a reference of the object (instead of a copy). In PHP 5 objects are passed by reference by default.

allow for turning off

So it looks like right now it turns whatever less file you give it into a style.css in the uploads directory.
I would rather it compile the way a desktop compiler would, so from:
/less/styles.less into
/css/styles.css

That way I can just include /css/styles.css - and then once I was done working on the theme, I could turn off the wp-less compiling action, so it wouldn't keep running on every page load.

How can I do this?

Lockup on site move

When I moved the site with active wp-less, it locked up on target with wp_die() on load. Its cache files needed to be deleted in filesystem to get site working.

importing less file from outside themes directory

I'm trying to import a .less file from a folder inside the plugin directory. It doesn't compile the LESS when I do this. It works fine from within the theme's directory tree. Is it possible for me to import from elsewhere?

lessphp 0.3.7 and above has a new PHP api

The latest versions of lessphp requires a change to wp-less. From line 125 I have made the following changes:

// automatically regenerate files if source's modified time has changed or vars have changed
try {

    // load the cache
    $cache_path = "{$css_path}.cache";

    if (file_exists($cache_path))
        $full_cache = unserialize( file_get_contents( $cache_path ) );

    // If the root path in the cache is wrong then regenerate
    if ( ! isset( $full_cache[ 'less' ][ 'root' ] ) || ! file_exists( $full_cache[ 'less' ][ 'root' ] ) )
        $full_cache = array( 'vars' => $vars, 'less' => $less_path );

    // *** different approach to setting variables from php and compiling from cache ***
    $less = new lessc();
    $less->setVariables($vars);
    $less_cache = $less->cachedCompile($full_cache['less']);

    if ( ! is_array( $full_cache ) || $less_cache[ 'updated' ] > $full_cache['less']['updated'] || $vars !== $full_cache[ 'vars' ] ) {      
        file_put_contents( $cache_path, serialize( array( 'vars' => $vars, 'less' => $less_cache ) ) );
        file_put_contents( $css_path, $less_cache['compiled']);
    }
}

I would not necessarily make the changes yet though as lessphp 0.3.8 is not working particularly well for me at the moment and has introduced a heap of new bugs.

It might also be worth looking at the new output formatting (http://leafo.net/lessphp/docs/#output_formatting) options in order to compress the compiled CSS further.

Use WP-LESS in my plugin

It would be awesome if I could do something like...

add_action( 'wp_head', 'my_plugin_head' );

function my_plugin_head() {
  wp_enqueue_style(
    'my-plugin-foo',
    plugin_dir_url(__FILE__) . 'my-plugin-foo.less'
  );  
}

.. and the WP-LESS parser would kick in, allowing me to use LESS in my internal plugins (I would add WP-LESS as a dependency to my plugin as well)

Let me know, thanks!

Import problem when attempting to use variables file second time

I have base.less stylesheet which includes colors.less. Importing works well, I can use @color-red color in base.less.

When I use second stylesheet project.less which also includes colors.less, it does not loads defined variables.

The problem is caused by last change in lessc.inc.php.

if (isset($this->allParsedFiles[realpath($realPath)])) {
  return array(false, null);
}

Second try to import colors.less breaks tryImport function because it was already loaded and does not injects colors.less variables.

If I comment out return line, it works well again.

Best practice for generating less?

Hi Robert,

Think this is particularly interesting for people who want to mask php files with the less content header in order to pass WP options or similar data through a less file (which isn't possible with the standard less integration), i.e.

@primarycolor: <?php echo get_option('primarycolor'); ?>;

Have you done any testing in that direction or had any experiences there yet?

Cheers!

Curious why WP-LESS gets added on the WP hook

Just curious why the WP-LESS processing gets added to the WordPress hook WP and not later so that themes & plugins can properly use wp_enqueue_scripts, wp_print_styles, and wp_print_scripts? to add their .less files.

Thanks for an awesome plugin!

WP Less Garbage Collection bloating DB

Hi there,

I have been using WP-Less for a while, and this issue has plagued me. For some reason the database is getting bloated in wp_options under the cron field, a serialized array is getting ridiculously large because of a 'wp-less_garabage_collection' value that is constantly being added.

This is actually forcing WordPress to crash under a "maximum execution time exceeded".

Thanks!

AJAX Conflicts

When using your WP Less code as part of a theme and including wp-less.php in my functions.php file, the LESS processing works a treat but it causes lots of AJAX issues when adding menu items, updating widget settings, quick editing categories etc. Basically anything that uses an AJAX call (I think) is just hanging with the loading wheel shown indefinitely. Removing wp-less.php stops the issue and everything works fine.

Package not in packagist

Your package aren't in packagist.

So if I add it to my composer.json file, I have the following error:

  Problem 1
    - The requested package icit/wp-less could not be found in any version, there may be a typo in the package name.

You can add it here: https://packagist.org/packages/submit

Thanks.

Alternate content dir name lets the preg_match fail

function parse_stylesheet() LINE 47:

According to this info on WPSE chat, the var $src_bits should get populated, which isn't the case in my install 1).

The problem is the hard coded wp-content dir inside the preg_match. Gladly there's an easy fix (not so easy getting to this point, but here it comes:

preg_match( "/^(.*?\/" . WP_CONTENT_FOLDERNAME . "\/)([^\?]+)(.*)$/", $src, $src_bits );, which worked fine in my test.

Additional note: In case you want to move the /uploads folder, you'll have to use the UPLOADS constant. It normally shouldn't get used, as it's defined when ms_default_constants() is run (only multisite), but you can simply set define( 'UPLOADS', trailingslashit( '/'.WP_CONTENT_FOLDERNAME ).'custom_uploads_name' ); in a single site install and it will just work, as the public dir struct function wp_upload_dir() sets it up, when it was defined: $dir = ABSPATH . UPLOADS;.

1) wp-content is renamed to content and wp-less is residing in a custom theme directory (alternate to default) and inside the following structure: /theme_dir/lib/less/.

Static init function

Could we have a static init function, like (for example) the following:

    /**
     * Creates a new instance. Called on a hook.
     * May be used to access class methods from outside.
     *
     * @see    __construct()
     * @return void
     */
    public static function instance()
    {
        NULL == self :: $instance AND self :: $instance = new self;
        return self :: $instance;
    }

or something like this:

    /**
     * Handler for the action 'init'. Instantiates this class.
     * 
     * @return void
     */
    public static function init()
    {
        $class = __CLASS__ ;
        $GLOBALS[ $class ] = new $class;
    }

...instead of this

    // initialise
    $wp_less = new wp_less();

This would allow us, to hook the class to a specific hook instead of wrapping the require() in a function and then hooking this function to the needed hook.

PHP Warnings on WP Update Page

Every time loading the WordPress updates page, this warning appears:

Warning: Attempt to modify property of non-object in /packages/wp-less/wp-less.php on line 124

Warning: array_search() expects parameter 2 to be array, null given in /packages/wp-less/wp-less.php on line 125

Warning: Attempt to modify property of non-object in /packages/wp-less/wp-less.php on line 125

I've included the WP-LESS package not as a plugin, but as part of the theme itself. This only began happening recently, around WP version 4.3. It is happening in every theme and every server environment that I have which employs WP-LESS.

Installation instructions vague for newbies.

I'm new to Wordpress development and don't understand where to install the plugin to have it required in my theme. You say to clone the git repo, but in what directory? Also, I'm unfamiliar with whatever Composer is.

As this is the first time I've touched such things it would be great if you could expand the installation section a bit more so that it doesn't imply that the developer has prior knowledge about the framework.

Thanks.

Allow for plugins/themes to require wp-less via composer

It would be nice if I could composer require wp-less from a plugin or theme folder as a way of installing wp-less.

Currently due to the "type": "wordpress-plugin" if you try this wp-less will end up in /wp-content/themes/{yourtheme}/wp-content/plugins/wp-less and wp-less' dependencies will be put in /wp-content/themes/{yourtheme}/vendor. wp-less.php is not designed for this structure as it expects that either it's a plugin or that the vendor folder is relative to it.

@include'ing from a variable?

Howdy.

The following doesn't seem to work:

In functions.php

function lblg_less_vars( $vars, $handle ) {
    $vars['layout'] = '3-columns-fixed-sb-right';
    return $vars;
}
add_filter( 'less_vars', 'lblg_less_vars', 10, 2 );

In the .less file:

@import "@{themeurl}/layouts/less/@{layout}.less";

This results in:

@import "http://localhost:8888/3.1/wp-content/themes/elbee-elgee/layouts/less/3-columns-fixed-sb-right.less";
.liststyle {
  list-style: none;
  margin: 0;
  padding: 0;

...etc.

What am I doing wrong? Is this even possible?

wp-less-cache breaks relative URLs

I'm using wp-less in a theme and expected that I could do a url(images/foo.png) as normal with less and css. However because the compiled css is moved to /wp-content/uploads/wp-less-cache/ and the url() is left as-is the path become broken.

Decouple code definition and execution

Since plugin seems to be growing beyond thin lessc wrapper it started as, I suggest we start to break out classes and function definitions into separate files.

Opinions?

LESS variable updating in cache but not in CSS

I am including wp-less in my theme, But I am stucked.
I am changing variable from get_option, like:

$vars['headerBG'] = get_option('color_header');

And I am calling this variable in theme.less, Like:

header{
    background: @headerBG;
}

Everything work fine until here, Compile result is :

header{
    background: #333333;
}

now if I change value of get_option('color_header')
then as usual cache file theme.less.cache and theme.less.css get updated.
Variable @headerBGs new value was updated in cache files but not in css files.
NOTE: CSS file is recompiling but color is not updating.

That is my problem!
please help me to fix it.

Plugin comment

Short Q: Why isn't this a plugin? Just to avoid the require...

Less File Not Found/Handled in Plugin Using WP-Less

Hello

I am attempting to use WP-Less in my plugin. I am hoping its possible to use WP-LESS in a plugin? This would save me alot of time if its possible. Also does WP-LESS compile less server side or is less handled client side - hopefully its server side.

I have a very simple Plugin that imports WP-LESS and an admin page should show its working by having some text styled. But the text isn't styled and its not finding the main.less file (its says its not found). Below are details of the error and the simple code - see the attached images for the error output and plugin directory structure.

capture2

![capture](https://cloud.githubusercontent.com/assets/10113201/9029031/f3f77c08-39ce-11e5-9635-f28e9b525a45.PNG)

Plugin Code:

/**
*  Plugin Name: TEST Load Less
*  Plugin URI: NA
*  Description: Test Development Plugin
*  Version: 1.0.0
*  Author: NA
*  Author URI: NA
*  License: GPL2
*/ 


add_action('admin_menu', 'TEST_admin_menu');
add_action('admin_init', 'include_less');
add_action('admin_print_scripts', 'include_less');
add_action('admin_print_styles', 'include_less');
add_action('admin_enqueue_scripts', 'TEST_enqueue_scripts');
add_action('wp_enqueue_scripts', 'TEST_enqueue_scripts');

// What action should less be included in? admin_init?
function include_less() {
    require_once( 'wp-less/wp-less.php' );
}

function TEST_admin_menu() {
    include_less();

    add_menu_page('TEST_DEV', 'TEST_DEV', 'administrator', 'TEST_DEV_SLUG', 
                    'show_TEST_page', 
                    plugins_url('images/help.png', __FILE__));
}

function TEST_enqueue_scripts() {

    require_once( 'wp-less/wp-less.php' );
    wp_enqueue_style( 'less-style', plugins_url( '/main.less', __FILE__ ) );
}

function show_TEST_page() {
    ?>
    <div class="wrap">
        <div>
            <p>No styling</p>
            <button class="btn">Abcdef</button>
        </div>

        <div class="my-less-namespace">
            <p>I should have styling from my less file</p>
            <button class="btn">Abcdef</button>
        </div>
        </div>
    <?php
}

?>```


Pulling latest lessphp

Hey buddy, lot of recent fixes to lessphp, mind pulling in latest for all its glory :) Cheers!

Possibility to abort silently with "wrong" .less file name

[function parse_stylesheet LINE 43](1. function parse_stylesheet LINE 43: if %28 ! strstr%28 $src,) ) will also return true if the filename is for e.g. sense.less.php and therefore fail silently.):

if ( ! strstr( $src, '.less' ) ) will also return true if the filename is for e.g. sense.less.php and therefore fail silently without any user feedback...

WP Less Garbage Collection bloating DB

Hi there,

I have been using WP-Less for a while, and this issue has plagued me. For some reason the database is getting bloated in wp_options under the cron field, a serialized array is getting ridiculously large because of a 'wp-less_garabage_collection' value that is constantly being added.

This is actually forcing WordPress to crash under a "maximum execution time exceeded".

Thanks!

Implement WP_Filesystem API for writing/reading files

This is aiming to make the plugin more embeddable in themes, it will have to use the filesystem API if it's to be able to pass the theme checker for hosting on wp.org. Also it makes for better security.

Of course it also depends on lessphp itself so may be a no go.

Parsing Variables

I must be dumb or something, but isn't:

function my_less_vars( $vars, $handle ) { $vars[ 'color' ] => '#000000'; return $vars; }

...supposed to be something along the lines of ...

function my_less_vars( $vars, $handle ) { $vars[ 'color' ] = '#000000'; return $vars; }

The first would just error out?

edit: oops fixed

Add ability to refresh-compile via AJAX

Problem to be solved is not having to reload the whole page to see changes in the LESS file.

I am imagining a wp-less built-in, but probably optionally loadable (filter?), JS component, that binds a keyboard key (F9 + filter?) to trigger an AJAX request for wp-less to recompile specified stylesheets. Then it would make the browser reload all or just the specified stylesheets in the fashion of http://livejs.com

Stylesheets array should probably be injected to the page as JS variable during initial page load. It's probably the best way to know exactly what stylesheets the user is working with.

This focuses on having a server-only work environment. Obviously for locally controlled environments it's possible to combine a reasonable light-reload solution from various existing pieces.

Thoughts? Anyone else interested?

Notice: wp_enqueue_style was called incorrectly.

For anyone receiving ' Notice: wp_enqueue_style was called incorrectly.' message during debug the solution is below.

if ( ! is_admin() )
add_action( 'wp_enqueue_scripts', 'wp-less_add_mytheme_stylesheet' );

function wp-less_add_mytheme_stylesheet() {
wp_register_style('mytheme', get_template_directory_uri() .'/style.less', array(), '', 'screen, projection');
wp_enqueue_style( 'mytheme' );
}

Hope that helps someone out. Great work on this by the way .

Fix cache refresh when switching themes

Using the code included in two different themes, switching between themes doesn't update the cache so the newly selected theme still displays using the old stylesheet.

W3 Total Cache

Keep running into trouble trying to get a recompile going when using total cache (usually means I have to do a mix of different stuff to try and trigger a refresh of the css). Maybe throw in a function to recompile whenever the w3 action/hook is fired? What do you think?

Dynamically change variables

Hello there,

I'm trying to combine wp-less with SMOF(https://github.com/sy4mil/Options-Framework) in my theme development.

SMOF uses variables that could be changed by users via admin options page. For example:

$of_options[] = array(  "name"            => "Background color",
                        "desc"      => "Set background color",
                        "id"              => "background_color",
                        "std"       => "#2C3E50",
                        "type"      => "color"
                        );

The following code is used in style.php and saved to css on the fly:

body {
background: <?php echo $data['background_color']; ?> <?php echo $background ?>;
}

It's kind of handy, but since all styles are written in less, wp-less is much more desirable.

Now, how can i use SMOF's variables here:

add_filter( 'less_vars', 'my_less_vars', 10, 2 );
function my_less_vars( $vars, $handle ) {
    // $handle is a reference to the handle used with wp_enqueue_style()
    $vars[ 'bg-color' ] = '#444444';
    return $vars;
}

Sorry if it's kind of stupid question, I'm new to wp & php.

Thanks!

Allow changing the wp-less-cache dir location

Example: I want to use Twitter Bootstrap together with WP Less.

The problem: Referenced icons/urls. Due to the fact, that WP Less is using the wp_upload_dir() function, I've no chance to use the default references. Going into the Bootstrap files and changing the location also is no option, as this would prevent updates without Bootstrap core changes.

One solution would be to use the filter in the WP core function, but I don't know how I could check if the actual call comes from WP Less, to not interrupt other parts of WP.

IMHO the best solution (I can imagine) would be a filter to move the cache folder location around.

add LESS from string

Hi,

I would like to add some less content from a string rather than from a file because it'll be dynamic
you think this a bad idea?
is it possible?

thanks!

Using variables/mixins in LESS files loaded separately from bootstrap.less

Hi,

I am using the wp-less plugin and have my bootstrap files setup like so:

- assets/
    - less/
        - global.less
        - bootstrap/
             - bootstrap.less
             - mixins.less
             - variables.less
             - required.less
             ... <all other boostrap less files>

I use the required.less file to import the mixins.less and variables.less files into my global.css type files:

@import "variables.less";
@import "mixins.less";

In my global.less file which contains all the application specific styles for my website, I am trying to import the required.less file at the top but it seems that It won't let me do it this way. I have done this before using LESS on another website without the plugin so it seems the plugin is causing the issue.

I get no console errors and my mixins/variables are not accessible to my global.less file:

@import "@{lessurl}/bootstrap/required.less"; 

.test-box {
    .border-radius(6px);
}

Have you come across this issue previously?

Thanks

Parse Error

Hello,

I'm using the less files from Twitter Bootstrap and whenever I update a less file I get this error exactly one time. After I get this error it doesn't appear again until change something in a less file.

parse error: failed at `@props: ~`"@{arguments}".replace(/[\[\]]|\,\sX/g, '')`;`
/path/to/my/site/wp-content/themes/my-theme/assets/css/less/mixins.less
on line 253

Here is line 253 from the mixins.less file.

.box-shadow(@shadowA, @shadowB:X, ...){
  // Multiple shadow solution from http://toekneestuck.com/blog/2012/05/15/less-css-arguments-variable/
  @props: ~`"@{arguments}".replace(/[\[\]]|\,\sX/g, '')`;
    -webkit-box-shadow: @props;
    -moz-box-shadow: @props;
    box-shadow: @props;
}

I've used Twitter Bootstrap and haven't had this problem so I'm assuming it is something to do with less. Any ideas what's going on?

Obsolete filter

As the less_vars filter already has the $handle as second arg, the 2nd - more specific less_vars_$handle - filter is obsolete.

I currently can check inside the 1st filter which $handle I'm using and then routing. I'd suggest to remove

  • the $handle from the first one OR
  • remove the 2nd - redundant - filter

It's no bug or blocker - just to remove any confusion.

WP_LESS not working with add_editor_style

Seems to be having difficulty running LESS files for the visual editor of WP. Based on the source code, add_editor_style simply adds the LESS file and isn't converting them to .CSS

With SSL

Sup!
If you have SSL set only on a checkout page, it's breaking styles as it's only served with http. Totally normal behavior, class wise. But not ideal.

I fixed it temp with Wordpress HTTPS http://wordpress.org/plugins/wordpress-https/

I'm wondering if there's a more elegant way to handle this?

Fix assumption that stylesheet is in content directory

parse_stylesheet() currently assumes that stylesheet resides in content directory tree. This is typical, but not guaranteed since WP themes and plugins can be decoupled from that directory by configuration, as well as completely arbitrary styles can be enqueued.

list( $less_path, $query_string ) = explode( '?', str_replace( WP_CONTENT_URL, WP_CONTENT_DIR, $src ) );

Since stylesheet registration only captures URL, we need to:

  • enumerate which kinds of locations for stylesheets are supported
  • implement their detection and processing

Why is `themeurl` hardcoded?

In https://github.com/sanchothefat/wp-less/blob/master/wp-less.php#L122 the themeurl is hardcoded to get_stylesheet_directory_uri(), why is this not set to the basedir of the enqueued less file? That way, less files can always use relative URLs to their location automatically.

Currently I am hooking into less vars to adjust it, but the filter is only given the handle, so it's not easy to do it automatically.

Let me know if I am misunderstanding that themeurl is doing.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.