Mengalihkan halaman web dari browser i.e UC Browser ke lainnya

Terkadang ada browser/penjelajah web tertentu yang Anda tidak inginkan untuk menampilkan halaman situs/web Anda, dan mengalihkannya ke browser lainnya, misalnya dari UC Browser ke Chrome. Adapun beberapa alasan kenapa ingin redirect atau mengalihkannya, seperti:

  • Tampilan situs tidak bagus, seperti kode html, css ataupun script lainnya tidak dapat dibaca.
  • Ada beberapa kode/script dalam situs yang tidak mendukung untuk ditampikan di browser tersebut, misal script iklan, video, slider dan lainnya diblokir.
  • Adanya beberapa fitur dari browser tersebut yang mengganggu navigasi halaman situs.

Cara yang sederhana dengan menerapkan kode JavaScript berikut ini di situs Anda supaya membuat pengunjung beralih ke browser lain.

Contoh sederhana untuk beralih dari UBrowser/UC Browser ke browser Chrome.

<script type='text/javascript'>
var ua = navigator.userAgent || navigator.vendor || window.opera,
    userAgent = ua.toLowerCase(),
    desktopURL = '//www.google.com/chrome/',
    mobileURL = 'googlechrome://navigate?url=', //URL Scheme opener
    loc = window.location;

//create condition to search match user-agent i.e ubrowser or ucbrowser
if ( /ubrowser|ucbrowser/i.test( userAgent ) ) {

    //create condition if it's mobile, if chrome installed it will be open new browser
    if ( /android/i.test( userAgent ) ) {
        loc.href = mobileURL + loc.href;
    }

    //if not installed, push user to download the browser in mobile or desktop
    setTimeout( function() {
        if ( window.confirm( 'This page ' + loc.href + ' is best viewed with Chrome browser. Download sekarang?' ) ) {
            loc.href = desktopURL;
        } else {
            loc.replace( desktopURL );
        }
    }, 2500 );//timeout in milliseconds
}
</script>

Untuk tampilan mobile, peralihan ini tidak bisa serta merta dilakukan jika pengunjung tidak meng-install aplikasi browser Chrome di smartphone-nya. Oleh karena itu dibuatlah tampilan dialog pesan kepada visitor untuk download browser tersebut terlebih dahulu.

Menerapkan di blog WordPress

Jika menggunakan WordPress, kode ini dapat dikembangkan sedikit dan membuat dialog untuk menampilkan pesan download.

add_action( 'wp_footer', function() {
    //set user agent i.e 'ubrowser|ucbrowser'
    //argument variable in js
    $args = [
        'text'      => [
            'button' => __( 'Download Now', 'bbccn' ),
            'title'  => __( 'This page is best viewed with Chrome browser', 'bbccn' )
        ],
        'url'       => [
            'icon'    => '//lh3.googleusercontent.com/nYhPnY2I-e9rpqnid9u9aAODz4C04OycEGxqHG5vxFnA35OGmLMrrUmhM9eaHKJ7liB-=w20',
            'mobile'  => 'googlechrome://navigate?url=', //URL Scheme opener
            'android' => '//play.google.com/store/apps/details?id=com.android.chrome',
            'ios'     => '//itunes.apple.com/us/app/chrome/id535886823',
            'desktop' => '//www.google.com/chrome/'
        ],
        'userAgent' => 'ubrowser|ucbrowser'
    ];

    //add filter to change value of js variables
    $args = apply_filters( 'args_variable_js_bbccn', $args );

    printf( "<script type='text/javascript'>\n/* < ![CDATA[ */\nvar jvL10n=%s\n/* ]]> */\n</script>\n", json_encode( $args ) );
    ?>
<script type='text/javascript'>
  var checkUA = function() {
    var pattern = new RegExp( jvL10n.userAgent ),
        ua = navigator.userAgent || navigator.vendor || window.opera,
        userAgent = ua.toLowerCase(),
        curURL = window.location.hostname + window.location.pathname,
        newBrowserURL = jvL10n.url.mobile + curURL;

    //create condition to search match user-agent i.e ubrowser or ucbrowser
    if ( pattern.test( userAgent ) ) {
        //open new browser + current url in mobile
        if ( /android/i.test( userAgent ) )
            window.location.href = newBrowserURL;

        if ( /ipad|iphone|ipod/.test( userAgent ) )
           window.location.href = newBrowserURL.replace( 'navigate?url=', '' );

        //create dialog + button
        setTimeout( function() {
            var div = document.createElement( 'div' ),
                layer = div.cloneNode( true ),
                h3 = document.createElement( 'h3' ),
                button = document.createElement( 'button' ),
                title = document.createTextNode( jvL10n.text.title ),
                btnTxt = document.createTextNode( jvL10n.text.button ),
                url;

            h3.appendChild( title );
            button.setAttribute( 'style', 'background:#800000 url('+ jvL10n.url.icon +') left 5% center no-repeat;color:#ffffff;padding-left:33px' );
            button.appendChild( btnTxt );
            layer.className = 'bbccn';
            layer.setAttribute( 'style', 'background:#ffffff;opacity:0.8;width:50%;border:1px solid #efefef;padding:50px;position:fixed;z-index:99999;top:50%;left:50%;transform: translate(-50%, -50%);text-align:center' );
            div.setAttribute( 'style', 'opacity:0.85;background:#000000;width:100%;height:100%;position:fixed;z-index:99998;top:0' );
            layer.appendChild( h3 );
            layer.appendChild( button );
            document.documentElement.style.overflow = 'hidden';
            document.body.appendChild( div );
            document.body.appendChild( layer );

            //show dialog
            if ( /android/i.test( userAgent ) ) {
                url = jvL10n.url.android;
            } else if ( /ipad|iphone|ipod/.test( userAgent ) && !window.MSStream ) {
                url = jvL10n.url.ios;
            } else {
                url = jvL10n.url.desktop;
            }

            button.addEventListener( 'click', function() {
                window.open( url );
            }, true );
        }, 2500 );//timeout in milliseconds
    }
  };
  document.addEventListener( 'DOMContentLoaded', checkUA, true );
</script><?php
  echo "\n";
}, 1000 );

Simpan kode tersebut di file functions.php theme WP Anda, dan buka situs (yang sudah di tambahkan kode di atas) melalui browser UBrowser/UC Browser untuk melihat cara kerja script ini.

Mengganti atau menambahkan user-agent
Jika ingin mengganti atau menambahkan user agent, cukup cari dan ubah kode ubrowser|ucbrowser kode di atas. Contoh tambah user agent “Opera” dan “Yandex”, maka ubrowser|ucbrowser|opera|yandex.

Atau, gunakan filter args_variable_js_bbccn tanpa harus mengubah kode tersebut. Tambahkan kode berikut di file functions.php theme Anda.

add_filter( 'args_variable_js_bbccn', function( $args ) {
    //add user agent separated by |
    $args['userAgent'] = $args['userAgent'] . '|opera|yandex';

    //change user agent
    #$args['userAgent'] = 'opera|yandex';

    return $args;
} );

Selain mengubah list user-agent, parameter value variable JS lainnya dapat juga diubah, seperti tulisan yang tampil atau url peralihan. Gunakan class name .bbccn untuk modifikasi CSS untuk tampilan dialog pesan.

URL Scheme Opener Mobile

  • firefox://open-url?url=http://example.com
    Membuka browser Firefox, tes berhasil dari Chrome IOS
  • googlechrome://navigate?url=example.com
    Membuka browser Chrome, tes berhasil dari UCBrowser Android
  • googlechrome://example.com
    Membuka browser Chrome, tes berhasil dari UCBrowser IOS
  • uc-url:example.com
    Membuka UC Browser, untuk Windows Phone 8.

Download dalam bentuk Plugin WP (Browser Blocking)

Kode JavaScript dalam plugin ini sudah dilakukan minifikasi untuk kode js-nya, serta penambahan terjemahan bahasa Indonesia. Silakan download, instal dan aktifkan tanpa perlu dilakukan pengaturan.

🔗 CCNINJA Browser Blocking v1.0.1

You are done! If any, your feedback would be really helpful.

Menampilkan Kotak Kutipan (excerpt box) di Page WordPress

Fungsi kotak Kutipan (excerpt box) di blog Wordress untuk memberikan penjelasan pendahuluan, singkat, atau inti akan tulisan dalam suatu artikel. Selain sebagai inti postingan, penjelasan tersebut juga berguna untuk dipakai sebagai content dalam meta description HTML halaman web atau halaman pos tersebut.

Banyak plugin WordPress khususnya yang terkait Search Engine Optimization, memanfaatkan isi dari excerpt ini untuk dijadikan meta description ataupun dalam meta open graph.

Pada dasarnya excerpt box untuk page post type itu tidak ditampilkan, hanya ada di post saja. Jika Anda ingin mengaktifkan dan menampilkannya, cukup dengan memasang kode berikut di file functions.php theme Anda.

add_action( 'after_setup_theme', function() {
	add_post_type_support( 'page', 'excerpt' );
} );

Hook yang digunakan adalah after_setup_theme dan kemudian memanggil function add_post_type_support. Isikan parameter dari function add_post_type_support $post_type dan $supports, sesuai dengan yang kita inginkan, dalam hal ini post type adalah page.

Pilihan Excerpt di Screen Options
Pilihan Excerpt di Opsi Layar (Screen Options).

Kotak excerpt akan aktif di halaman create/editing Page Anda, seperti halnya di post area. Jika Anda masih belum melihatnya, silakan tab Screen Options, dan centang Kutipan (Excerpt) untuk menampilkannya.

Vaping Laws around the World

As we all know, the world of vaping is ever changing. Like with many other laws on many other topics, there is very little consensus on the topic of vaping and whether or not it should be allowed. This can make things more than a little difficult for travelling vapers – where in one country you can vape freely, you might be given a substantial fine in the next. Here’s the most important rules and regulations you need to know from around the globe.

The EU

EU wide regulation introduced in 2014 outlaws advertising for e-cigarettes, sets a limit on the amount of nicotine in e-liquids, and requires sellers to package products in child and tamper-proof packaging amongst a whole load of other complicated rules and regulations. Despite the arrival of these rules, there are still discrepancies from country to country. In France, for instance, e-liquids are considered medical products – something that is not generally in place in other member states – and, in the United Kingdom, advertising of e-cigarette paraphernalia has been allowed since 2014.

North America

I’m sure we’re all familiar with the ever-changing regulations in the United States, but what about Canada? If you’re planning a trip across the border, there’s good news – vaping is largely unregulated in Canada. While the technicalities of Canadian law mean that selling e-cigarettes is illegal, the reality of the situation is that this is rarely enforced properly. When it comes to actually vaping, several cities have enforced different rules – in Toronto, for example, it’s against the rules to vape in the workplace and Vancouver has extended their smoking ban in public places to vaping.

Central and South America

After a ban on tobacco products was overturned in 2015, e-cigarettes are now legal again in Mexico. However, in places like Uruguay and Argentina vaping is completely banned. In addition, Brazilian law completely forbids ‘the sale, importation, and advertising’ of any electronic cigarettes. This is because Brazil’s health and sanitation federal agency, known as Anvisa, found the current health and safety assessments about e-cigarettes unsatisfactory to allow them in the country.

Australia and New Zealand

As vaping remains a relatively new phenomenon, Australia is still in the midst of developing their vaping regulations. Often the rules from state to state vary (and, in some cases, they actually conflict – which is nice and confusing for travellers!). But, on the whole, there is no regulation completely outlawing e-cigarettes.

In New Zealand, things are a little more straightforward. As long as your e-cigarettes don’t contain nicotine, sale is permitted to people over the age of 18. If you want e-juices containing nicotine, they must be imported from overseas and can only be used for personal use. Advertising of e-cigarettes is not allowed, however, which can cause trouble for manufacturers.

Asia

Japan took the decision to ban e-cigarettes containing nicotine in 2010, but there’s currently no regulation for e-cigarettes and vaping devices that don’t contain nicotine – so both adults and minors can vape those to their heart’s content. Similarly, in the Philippines, e-cigarettes remain completely unregulated, which means anyone of any age can buy them. However, the Philippine Medical Association is recommending that the ban on cigarettes in public places be extended to vaping.

In the modern-day home of vaping, China, the import and export, sale, and use of e-cigarettes is completely legal – but new rules are being imposed in certain places. In Shanghai, for example, the use of e-cigarettes is banned in no smoking areas.

The Middle East

Many countries in the Middle East take an even harder line against vaping. The UAE, Qatar, and Jordan have all completely banned vaping devices. Brunei goes one step further in their vaping rules, slapping anyone found vaping in a non-smoking zone with a $500 fine, and selling or importing e-cigarettes could cost you $10,000. If you’re planning to visit any time soon, we’d recommend you follow the rules!

It’s important to remember that vaping regulations are always changing. Public opinion on vaping is always evolving, as are the thoughts of people in power. If you’re an avid vaper planning to travel over the next few weeks, we’d definitely recommend that you check up on the regulations in your destination – after all, it’s better to give up your e-cigs for a little while then end up with a hefty fine (or jail time!).

Using the_posts_pagination for custom page template WordPress

If you look my sitemap, you’ll see the list of my post with pagination. That page was created under custom page template, the custom WP_Query of post’s list build under main loop of page, and function the_posts_pagination to display pagination.

Here the sample PHP code that you can accomplish if you need create custom page template with pagination. Just add after your main query loop.

// Define page_id
$page_ID = get_the_ID();

// Define paginated posts
$page    = get_query_var( 'page' );

// Define custom query parameters
$args    = array(
	'post_type'      => array( 'post', 'book', 'movie' ), // post types
	'posts_per_page' => 5,
	'paged'          => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1
);

// If is_front_page "paged" parameters as $page number
if ( is_front_page() )
	$args['paged'] = $page;

// Instantiate custom query
$custom_query = new WP_Query( $args );

// Custom loop
if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) :
        $custom_query->the_post();

		/**
		 * Displaying content
		 *
		 * the_title(), the_permalink(), the_content() etc
		 * Or see Twentysixteen theme page.php
		 * get_template_part( 'template-parts/content', 'page' );
		 *
		 */
    endwhile;

		/**
		 * Pagination parameters of the_posts_pagination() since: 4.1.0
		 *
		 * @see the_posts_pagination
		 * https://codex.wordpress.org/Function_Reference/the_posts_pagination
		 *
		 */
		$pagination_args = array(
			'prev_text'          => __( 'Previous page', 'theme-domain' ),
			'next_text'          => __( 'Next page', 'theme-domain' ),
			'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'theme-domain' ) . ' </span>'
		);

		/**
		 * Fix pagination link base
		 *
		 * If in paginated posts w/o multiple loop
		 *
		 */

		if ( ! is_front_page() && 0 < intval( $page ) )
			$pagination_args['base'] = user_trailingslashit(
				untrailingslashit( get_page_link( $page_ID ) ) . '/page/%#%'
			);
		/**
		 * Fix Pagination with $GLOBALS['wp_query'] = {custom_query}
		 *
		 * @see get_the_posts_pagination use $GLOBALS['wp_query']
		 * https://developer.wordpress.org/reference/functions/get_the_posts_pagination/#source-code
		 *
		 */
		$GLOBALS['wp_query'] = $custom_query;
		the_posts_pagination( $pagination_args );
else :
	/**
	 * Empty Post
	 *
	 * Run your stuff here if posts empty
	 * Or see Twentysixteen theme page.php
	 * get_template_part( 'template-parts/content', 'none' );
	 */
endif;
wp_reset_query(); // Restore the $wp_query and global post data to the original main query.

We using get_page_link on paging arguments code instead of get_pagenum_link function, it just to making work with main loop if using post page ( wp_link_pages ~ <--nextpage--> ) for your content. I think there are better clean approach than this, but.. ah, let’s go ready to rumble.

UPDATE: April 08, 2016

  • Fix pagination if set in front page

Menampilkan editor TinyMCE di front-end tanpa wp_editor

Dengan function wp_editor Anda akan dengan mudah untuk menampilkan editor yang sama dengan editor postingan admin. Bagaimana jika kita ingin menampilkan hal yang sama dengan memanfaatkan langsung fitur TinyMCE yang digunakan oleh wp_editor?

Cara ini sudah saya terapkan di beberapa plugin private dan sudah saya share di WPSE.

Kode HTML sederhana textarea

Kode ini bisa Anda tempatkan di page situs Anda.

<textarea id="textarea_id_element"></textarea>

Kode PHP dan settingan TinyMCE

Dengan menggunakan function jv_editor_tinymce kita akan menempatkan kode js settingan tinyMCE di bagian footer theme. Pastikan Anda mengubah id name textrea dimana Anda akan menempatkan tinyMCE editor.

add_action( 'wp_footer', 'jv_editor_tinymce' );
function jv_editor_tinymce()
{ ?>
<script type="text/javascript">
if ( undefined !== window.jQuery ) {
	jQuery( document ).ready( function( $ ) {
		tinymce.init( {
			mode : 'exact',
			elements : 'textarea_id_element', //your id name textarea element
			theme: 'modern',
			skin: 'lightgray',
			menubar : false,
			statusbar : false,
			toolbar: [
				'bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | undo redo'
			],
			plugins :'paste',
			paste_auto_cleanup_on_paste : true,
			paste_postprocess : function( pl, o ) {
				o.node.innerHTML = o.node.innerHTML.replace( /&nbsp;+/ig, ' ' );
			}
		} );
	} );
}
</script>
<?php
}

Kode JS TinyMCE WordPress

add_action( 'wp_enqueue_scripts', 'jv_enqueue_scripts' );
function jv_enqueue_scripts() {
	wp_enqueue_script( 'tinymce_js', includes_url( 'js/tinymce/' ) . 'wp-tinymce.php', array( 'jquery' ), false, true );
}
Tampilan editor TinyMCE
Tampilan editor TinyMCE dengan menggunakan theme TwentySixteen.

Tutorial ini hanya sekedar dasar untuk menampilkan editor tinyMCE, untuk menggunakannya dalam hal mengirimkan data layaknya postingan, Anda membutuhkan form, tombol submit dan function untuk mengevaluasi data yang dikirim. Semoga bermanfaat.