Most Common Genesis Hooks and Filters – [WordPress]

I  will list all the most common Genesis hooks and filters used by me while developing a website without boring you with more contents.

For a basic overview of Genesis framework read here.

Genesis hooks filtersWhile customizing a WordPress,  use a child theme to make all your changes so your parent theme will remain clean.

Below mentioned are the common tasks achieved by Genesis hooks and filters while developing a website

  • Change number of columns in Footer.
  • Registering the custom sidebar
  • Hooking registered side bar to appropriate section
  • Change the default position of the primary menu
  • Remove the site title for Frontpage
  • Change the Copyrights content
  • Modify Breadcrumb Prefix and Format
  • Create a new custom post type.
  • Add the custom post to archive query.
  • Remove comments section on Custom post type

Add the following code snippets to the function.php of Genesis child theme.

Change number of columns in Footer

This line will be already there in the function.php. Increase or decrease the footer column count. You can see the respective number of footer sidebars registered in the widget area.

add_theme_support( 'genesis-footer-widgets', 3 );

Registering the custom sidebar

This code snippets let you create and register a custom sidebar which allows you to add the widgets to your website

genesis_register_sidebar( array(
 'id'          => 'Unique_id_for_custom_sidebar',
 'name'        => __( 'Name for Custom sidebar', 'theme_name' ),
 'description' => __( 'Description for custom sidebar', 'theme_name' )
));

Genesis Hooks to pull registered side bar to appropriate section

This Genesis hook method allows you to replace the sidebar content in the place of declared hook section
Refer here for Complete hook Guide.
You can add custom HTML wrapper to the custom sidebar with the help of “before” and “after” parameter.

add_action( 'genesis_header_right', 'menu_header_right');
function menu_header_right() { 
 if (is_active_sidebar( 'menu_header_right' ) ) { 
   genesis_widget_area( 'menu_header_right', array( 
    'before' => '<div class="menu_header_right widget-area"><div class="wrap">',
    'after' => '</div></div>', ) );
 }
}

Change the default position of the primary menu

These Genesis hooks allow you to change the default position of the primary menu by removing it from default position and add it to the appropriate section using the hook name.

here I remove the primary menu from its default position and add it to genesis_header_right

remove_action( 'genesis_after_header','genesis_do_nav' ) ;
add_action( 'genesis_header_right','genesis_do_nav' );

Remove the site title for Frontpage

Remove the title section of the page if it is front page using condition and remove action.

add_action( 'get_header', 'remove_title_frontpage' );
 function remove_title_frontpage() {
  if ( is_front_page()) {
  remove_action( 'genesis_entry_header', 'genesis_do_post_title' );
 }
}

Change the Copyrights content

Here am used a filter to change the content of the existing footer credits function. Replace the echo command content with the appropriate HTML code.

add_filter( 'genesis_footer_creds_text', 'footer_creds_text' );
function footer_creds_text () {
	echo 'Custom HTML Code';
}

Modify Breadcrumb Prefix and Format

Modify the args[‘sep’] value to change the breadcrumb separator. You can also add the prefix to the breadcrumb. Here am adding a single space for better visibility and readability.

add_filter( 'genesis_breadcrumb_args', 'custom_breadcrumb' );
function custom_breadcrumb( $args ) {
  $args['labels']['prefix'] = '';
  $args['sep'] = ' > ';
  return $args;
}

Create a new custom post type

By creating a custom post type you can have a separate post section under WordPress admin menu with given name. The below code snippet will create custom post type “News” and add it to the WordPress admin menu. Change the values from “News” to require name if you want to create your own post type

add_action( 'init', 'create_custom_post_news' );

function create_custom_post_news() {

	$labels = array(
			'name' => __( 'News' ),
			'singular_name' => __( 'News' ),
			'all_items' => __('All News'),
			'add_new' => _x('Add new News', 'News'),
			'add_new_item' => __('Add new News'),
			'edit_item' => __('Edit News'),
			'new_item' => __('New News'),
			'view_item' => __('View News'),
			'search_items' => __('Search in News'),
			'not_found' =>  __('No News found'),
			'not_found_in_trash' => __('No News found in trash'),
			'parent_item_colon' => ''
			);

			$args = array(
			'labels' => $labels,
			'public' => true,
			'has_archive' => true,
			'exclude_from_search' => false,
			'menu_icon' => 'dashicons-admin-post',
	    'rewrite' => array('slug' => 'news'),
	     'taxonomies' => array( 'category', 'post_tag' ),
	      'supports'  => array( 'title', 'editor', 'thumbnail' , 'custom-fields', 'excerpt', 'comments', 'genesis-cpt-archives-settings' )
	 );

		register_post_type( 'news', $args);

}

Add the custom post to archive query

The newly created custom posts are not available in the search result of the website.  Add the newly created post to the archive with the following code.
Add the name given in register_post_type to the $query->set( ‘post_type’, array()) seperated by coma

add_action('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if($query->is_main_query()
    && ( is_category() || is_tag() )) {
        $query->set( 'post_type', array('post','news') );
  }
}

Remove comments section on Custom post type

Here I removed the comment section for the custom post type news.

add_action( 'init', 'remove_custom_post_comment' );

function remove_custom_post_comment() {
    remove_post_type_support( 'custom_post_name1', 'comments' );
}

These are the most commonly used hooks and filters while developing the normal website. Start developing your WordPress site with Genesis framework.

Genesis Framework Simple Reference Guide

In Genesis Framework Simple Reference Guide, Let’s start with a small intro about Genesis framework. Genesis framework is most flexible WordPress theme with more customization option. Genesis framework let you develop a site on WordPress in a way you want it. If you prefer WordPress for development this framework will give you more power and flexibility to develop the website. You can create your own customized theme using Genesis framework.

Genesis Framework Simple Reference Guide

 

Genesis framework is one-time purchase.

So, it’s worth buying and use it for multiple site development

Genesis Framework Simple Reference Guide

Genesis framework’s customization based on the hooks, filters. Using these options you can develop a website right from the scratch.

Hooks –   Inject the desired code at desired place without changing any WordPress default file.

Filters – allow you to modify/decorate  the existing function

Download and install the Genesis Theme and also install the child theme for Genesis and activate it.

Do all the customization in child themes function.php

This will keep the parent theme clean.

You can put your custom contents section in the required place by creating/registering the sidebar and  hook it in function.php ( child theme)

Refer the below image for the Genesis Hook guide

Genesis Framework Simple Reference Guide

the hook guide will help you to understand the names given to refer section of the website. Use this hook name to replace it with required custom contents.

Registering sidebar in Genesis

If you want to put your custom HTML code or content in place of the hook names, first you need to register the sidebar. The registered sidebar will appear in the Appearance – > Widget section of the WordPress.

Once the register sidebar appears in the widget section drag drop the require widget to the corresponding sidebar. You can also insert custom content blocks to the registered sidebar. These content block let you add custom codes.

genesis_register_sidebar( array(
 'id'          => 'menu_header_right',
 'name'        => __( 'Menu - Header Right', 'custom_name' ),
 'description' => __( 'custom_description.', 'custom_name' ),
) );

Add the above code snippet to the child themes function.php. Now you can see the new sidebar available in widget page with the name mentioned in the code.

Genesis Framework Simple Reference Guide

Hook the registered sidebar

After registering the sidebar,  we need to determine the place where the appropriate sidebar needs to be hooked.

add_action( 'genesis_header_right', 'menu_header_right');

function menu_header_right() {
 if (is_active_sidebar( 'menu_header_right' ) ) {
   genesis_widget_area( 'menu_header_right', array(
  'before' => '<div class="menu_header_right widget-area"><div class="wrap">',
  'after' => '</div></div>',
  ));
 }
}

This piece of code will hook the custom sidebar in the place of  “genesis_header_right”  as mentioned in the hook guide. With the help of  ‘before’ & ‘after’ attribute, you can wrap side bar with a custom HTML & class for styling.

Genesis Filters

Filters in Genesis tends access to modify the result of the existing function. I will explain the filter concept with the example.

In a breadcrumb, the default separator will be “/” and the breadcrumb will look like “Home/some_page” If I want to modify the default separator of the breadcrumb from “/” to “>” which can be achieved by filters.

function change_breadcrumb_separator( $args ) {
   $args['sep'] = ' > ';
   return $args;
}
add_filter( 'genesis_breadcrumb_args', 'change_breadcrumb_separator' );

Genesis general settings

Apart from the custom hooks & filters Genesis framework has some general settings.

  • Default site layout
  • Section for adding logo image
  • Breadcrumb options
  • Comment and Track Backs
  • content archive
  • Blog page template
  • Header / footer scripts.

These titles itself reveal the core purpose of the settings.

Genesis framework simple reference guide gave a basic idea about implementation for more hooks and filters visit the link below.

Most common hooks in genesis framework used for website development are available here.

Ready made themes also available in Genesis framework. Check it out!

Setup Sass In Create-React-App Without Ejecting

If you are using Create-React-App module to manage your no configuration react application development environment, this guide is to setup Sass compiler into the environment without ejecting the setup.

Setup Sass In Create-React-App Without Ejecting

We know create-react-app comes with eject option, which will deploy all automatic confirmation to manual configuration, Even for a professional developers, it will be a headache while doing an upgrade in future. Currently, the create-react-app doesn’t come with Sass compiler but we can integrate it out of the box. This tutorial is to explain how to setup Sass compiler in the existing/new application without ejecting.

Node and NPM needs to be installed before continuing following steps.

Step 1:

Create react app using create-react-app by following syntax

npm install -g create-react-app
create-react-app
my-app cd my-app/
npm start

Step 2:

Install node-sass-chokidar from npm

npm install --save node-sass-chokidar

Step 3:

Open package.json and add the following into scripts configuration.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive” }

To watch sass and compile use following command

npm run watch-css


Step 4:
Sometimes we miss to run the command while running the application, So let’s add this watch css to the application run command.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive”,

 

“start”: “react-scripts start”,

 

“build”: “react-scripts build”,

 

“start-js”: “react-scripts start”,

 

“start”: “npm-run-all -p watch-css start-js”,

 

“build”: “npm run build-css && react-scripts build”, }

now we don’t need to run separate commands to compile css.
Now running

npm start

and

npm run build

The command builds Sass files too.

Password protection to Website using htaccess

Password protection to Website using .htaccess is much easier than you ever think. This .htaccess authentication is not only for protection. As a developer, we always have multiple staging and dev environment before production. So authenticating those web servers with .htaccess is recommended.  Especially authenticating website with .htaccess will protect your environment from unauthorized access and unwanted SEO crawlings.

password protection htaccess

The site protected with htaccess will prompt for the authentication whenever it gets the hit. 

You can setup this .htaccess authentication within two simple steps.

  • Create encrypted password file.
  • Configure and map the password file in .htaccess

Creating an encrypted password file

First of all, create a new password file in the document root. This password file will hold all username with the respective password in encrypted format. Each encrypted username and password will be in new line. You can create your own encrypted username and password set without relying on any online tools.

$ htpasswd -nbm username Password

Copy the generated encrypted password to the password file.

 “myName:$2y$05$LwGdq19WrsD9w0VzFg0ZuetbL5/bw.S7yyDsjj1rXS13buZuWRBNW”

Note: Give desired random file name to the password file preceded with “.” .

htpasswd command executable is found in the apache/bin if you are using XAMPP in local dev machines. 

 

Configure and map the password file in .htaccess. 

We are almost done, the next thing is to add the below mention lines to your .htaccess file in the document root.

AuthType Basic
AuthName "My Protected Area"
AuthUserFile /absolute/path/to/password/file
Require valid-user

Note:

  • in addition use the full absolute path in the AuthUserFile . If you use relative path it will result in 500 Server error
  • If you use relative path / password file is not accessible  will result in 500 Server error

As a result, you can see an authentication popup whenever you hitting the URL freshly.

htaccess authentication

 

Know furthermore about the encryption options available.

Know furthermore about the htpasswd attributes

Popular Frontend Framework you must try at least once.

Web development reaches new era after the HTML5 and CSS3. The frontend framework is the first thing hits our mind whenever we hearing the word “Let’s develop a new website”. While architecting the project everyone prefer to use the popular front-end frameworks.

frontend-frameworks

This is common that the people like to walk on their legs, Some crazy guys do it by hand, am sure it will be more fun while walking with hands. similarly, I decided to try some of the frontend frameworks which are not that frequently used as Bootstrap and Foundation.

Let’s have some fun!

Here come the heads up for some framework I tried.

Materialize

materialize

Materialize is a modern responsive framework based on the Google’s material design. The materialize frontend framework also support SCSS (CSS preprocessor). It had its own package of icons, button styles, cards etc. The developer who knows less about designing and want to implement the material design then this is the right pick.

Materialize have their own portal for showcasing the websites which are developed using their framework

UIKit

uikit css

UIKit is one of the remarkable frontend frameworks which has the both LESS  & SCSS support. It is considered as highly modular front end framework. The special admiring part of the framework is the naming conviction used for the class.

This framework suits for the developer who have basic knowledge on front end development.

Pure

pure

Pure is a remarkable responsive framework from the popular brand YAHOO! It’s well known for its light weighted CSS modules. Pure doesn’t have JS support library.

Pure is preferred for the developer who wants to develop a responsive site rapidly with lightly weighted frontend framework.

Skeleton

skeleton css

Skeleton is more light weighted when compare to Pure as it only has the basic modules to build a responsive design.  Even though it is lightly weighted skeleton is bare enough to develop a small responsive web application. It also have the responsive grids, and basic components like buttons, forms, table, list etc.

The web development doesn’t require all the styling of the large framework then skeleton is a preferred choice

Numerous frameworks are available now., in which I listed the frameworks that I  tried and admired.

Angular directive that dynamically change input box width respective to the placeholder

Recently I get with a requirement to dynamically change input box width respective to the placeholder length. Now I am going to give a small heads up about use case and how I accomplished the task.

dynamically change input box length

Mission:

This application is developed with angularJs. As it has multiple language support placeholder also changes respective to the language. For some of the language, placeholder is not fully visible and for some of the language, the input box width was too large compared to the placeholder. So here the mission is to dynamically change the width of the input box respective to the placeholder length.

Mission Accomplished.

To accomplish the above mission I create a custom directive to change the width of the input box dynamically. Here the challenge is to find the width of the placeholder. The length property of the placeholder will give you the character count. Using that we can’t able to find the element width of the placeholder text.

In this directive, I used two key things to find the width of the placeholder text

  1. Font size – this will get the current font size used in the input box
  2.  <span> – Sudo element to calculate the actual element width of the placeholder

Calculating the Font Size

The below given js code will return the font size used in the input box which invoked this directive

var fontSize = parseFloat(window.getComputedStyle(elem[0], null).getPropertyValue('font-size'));

Pseudo Element

After that dynamically create a pseudo element with the style of above identified font size because this will help us to get the exact width of the placeholder content. Once the process of identifying the width is donr then the pseudo element got removed from the DOM.

Options

minwidth – in addition, this attribute will set the minimum width for the input box

bufferwidth – in addition, this attribute will add buffer with for input box for better readability and appearance.

Angular Directive to Dynamically Adjust input box width respective to the placeholder length

Code Snippet

See the Pen Angular Directive to Dynamically Adjust input box width respective to the placeholder length by icodefy (@icodefy) on CodePen.

You can find the working snippest here. Drop your suggestion and valuble comments.

Image zoom for e-commerce

Folks this time lets make some fun with implementing product image zoom for e-commerce site by using jQuery and customizing some jQuery plugins. Now lots of new frameworks and libraries available for the JavaScript. Even though jQuery still hold its better position. It is still used because of its flexibility and easy manipulation of the dom elements.

Mission

Today the mission is to implement a product zoom for a popular e-commerce site which is using jQery for dom manipulations.

Mission Accomplished

Lots of zoom plugins are available online wits lots of various features. Here am not going to give you a plugin and make you use the same for your implementation.

Am just going to explain how I implemented a product zoom by customizing already existing free plugins. sure, this combination and customization will give you a pro look for the product display page’s zoom image.

This customized product zoom has some remarkable function apart from the zooming product image. It holds the enlarged gallery and MegaEnlarge through which you can view the product more clear.

Just Download and go through the code I used simple HTML and Jquery in the way that everyone can understand. Go through the comments in zoom.js & index.html for more clarity.

Demo   |   Download

This jquery zoom implementation has four features

  1. Vertical Thumb image gallery carousel.
  2. Product Zoom
  3. Enlarged Gallery
  4. Mega Enlarge

Vertical Carousel

iZoom - ecommerce product zoomProduct Zoom

iZoom - ecommerce product zoom

Enlarged Gallery

iZoom - ecommerce product zoom

Mega Enlarge with PanZoom

 

Hotlink for demo and the working example links are dropped below just check it out!

Demo   |   Download

Plugin Credits

Product Zoom: ElevateZoom  [Free Plugin with numerous options]

Vertical Thum Gallery Carousel: rcarousel  [ Support horizontal/vertical ]

Enlarged Gallery: Fancybox

MegaEnlarge : ImagePannign.

The comments section is opened for valuable suggestion.

Happy Coding!

 

Simple Method to Localize your Angularjs Project

Localize your Angularjs Project is so simple, Angularjs has its own l10n & i18n scripts which are responsible for localizing the date, number and currency into your project but it has some restrictions with it. If you want to load specific locale library from angular js it can be done it by adding the corresponding locale via the script tag. But in case if you want to change the locale or language inside the application while it is running without reloading the page then here comes a simple solution.

localize angularjs app

Mission

The mission is to implement localization into the project without injecting any third party modules “angular-translate” into our application.

Mission Accomplished

Now am going to brief how I implemented localization manually

  1. Creating resource.json for the different language which holds all your translation as a json object.
  2. Get the JSON data using “$resource” and assign it to an object under “$rootScope”.
  3. Copy new locale object of corresponding to the language to $locale.

Creating  separate resource JSON

I created a separate folder which holding the localization object for the different object. The final level holds the name of the Locale Id, which is going to decide in what language our application renders.

This is how the folder Structure for resource.json created

-app
|_ l10n
|__en-us
|____resource.json
|__de-de
|____resource.json

This resource.json holds all the static value of my app. In all my HTML I use the key to rendering corresponding value.

whenever the user changes the language I get the unique language ID and make a $resource call and get the appropriate resource.json to render the values in selected language.

The same resource.json holds my locale object which is responsible for the date, number & currency formats.

Angular Js localization module on GitHub

Access the above mention URL and open the required language JS and copy the locale object from corresponding js to your resource.json

sample resource.json with Static & locale values for the German language.

{
 "indexPage": {
    "welcomeNote": "Willkommen bei icodefy",
    "followUs": "Folge uns"
    },
 "homeMenu": {
    "home": "Zuhause",
    "aboutUs": "Über uns"
    },
"locale": {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"ERANAMES": [
"v. Chr.",
"n. Chr."
],
"ERAS": [
"v. Chr.",
"n. Chr."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"M\u00e4rz",
"Apr.",
"Mai",
"Juni",
"Juli",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Dez."
],
"STANDALONEMONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.y HH:mm:ss",
"mediumDate": "dd.MM.y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
}, {
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}]
},
"id": "de-de",
"localeID": "de_DE"
}
}

Get resource.json Data using $resource and copy to $locale

Whenever the user changes the value in the language dropdown I call the appropriate file URL using $resource request and get the resource.json and reassign it back the $rootScope.l10n which hold all the static value of the application.

Here $rootScope.lang is the value bind from the language dropdown which is changed by user.

$resource('/app/l10n/' + $rootScope.lang + '/resources.json')
  .get(function (data) {
            $rootScope.l10n = data;
            // inject LocaleFactory in controller
            LocaleFactory.setLocale($rootScope.l10n.locale);
        });       

LocaleFactory is created for the component reusability. The angular.copy function can also call directly.

.factory('LocaleFactory', function ( $locale ){
 return {
  setLocale: function (currentLocaleObj) {
  angular.copy(currentLocaleObj, $locale);
 }
};

Drop your valuable comments and improvement suggestions in the comment section.

Turn Google Bar chart into Tornado Chart (Butterfly Chart)

Google chart visualization provide multiple varieties of charts to addressing your data visualization needs. The good things about the Google chart are it had lots of customization option and also it is absolutely free to integrate and use with your web application. Google chart includes lots of inbuilt customization options, these options allow you have the better visualization. Even though it doesn’t have any Tornado chart in its library. But we can customize the google bar chart into Tornado Chart with some work around.

google-bar-chart-to-tornado-chart_new

As I got unique requirement from one of the projects, which is a rating and review kind of stuff developed with HTML5 & Jquery for frontend and Laravel 5 & SQL for the backend services.

Mission

Here mission is to show the user’s top 3 positive & negative ratings in a single chart. That Chart contains most liked components on its right and most disliked element on its left along with its average rating and element name as a label. While creating it with the google bar chart the challenge we faced is to make positive and negative values bar at the same level as shown in the figure below.

Tornado butterfly Chart

Mission Accomplished

While implementing google bar chart with negative values it’s not displayed as expected. so we need a workaround to make the chart look like as expected. By default, it displays the chart as shown below with positive and negative values at different levels of the y axis.

Default  google chart with negative valuesnormal google bar chart

Work Around in Google Bar Chart

To make this default bar chart to visualize like a required Tornado chart (Butterfly Chart) we need to do some work around. I will explain those option attribute added to the default chart option.

you can refer the JS part of the code snippet below in which the variable “option” inside “drawbarChart” function holds the additional options for chart visualization.

If you refer that variable in which we added the “isStacked” attribute to make the negative and positive values at the same level

isStacked: true,

we are getting data in ascending order from backend which holds smaller value at the first. But as per the requirement, we need to show the top rated value at first in the google Tornado chart. For invert the chart value we added the another attribute to the option “vAxis” object.

vAxis: {
direction: -1 ,
}

 

Code Snippet

See the Pen Customize Google Barchart into Tornado Chart (Butterfly Chart) by icodefy (@icodefy) on CodePen.

You can find the working code snippet above. Our comment box is open. Drop your valuable comments

Post Feeds to Facebook wall from Web / Mobile Application.

Under this topic, Am sharing that how I implemented a functionality to post feed to users Facebook wall. I used javascript HTTP post method and Facebook Graph API to achieve this.

Am taking a hybrid mobile application was developed using Ionic and AngularJs as an example. That application has the option to share user check-ins, favorites & activity kind of stuff.

Post to facebook wall from mobile applicaiton

Mission

The mission is to post the recent activity of the user to the Facebook wall if share to Facebook option is enabled. The another task is to display posted via “App_Name” and the link to the respective web page in the bottom of the feed.

Mission accomplished

To accomplish the mission of posting the user data to Facebook wall I used the HTTP post method and the Facebook Graph API as I mentioned above.

Code snippets

try {
 $cordovaFacebook.getLoginStatus()
 .then(function(success) {
   // save access_token
   var accessToken = success.authResponse.accessToken;
   var app_id = "Your App ID";
   var content = '&message=YOUR_CUSTOM_MESSAGE&link=YOUR_TARGET_LINK&caption=POST_VIA_NAME&picture=PICTURE_URL';
   var url = "https://graph.facebook.com/me/feed?app_id=" + app_id + "&access_token=" + accessToken + content;
   $http.post(url).then(function(response) {
    // success action
   });
  });
} catch (_error) {
  // Error action
} 

The above example of the application using Ionic & AngularJS

Note: you can use the url variable on any HTTP post or ajax calls

Code Brief

Getting the user login status before posting the feed

on success am getting the user auth token from facebook.

  • app_Id   = facebook developer application ID.
  • YOUR_CUSTOM_MESSAGE : The message to display in the feed
  • YOUR_TARGET_LINK: The URL to navigate if the user click on the Facebook post
  • POST_VIA_NAME : Application / Website name.
    PICTURE_URL: URL of the picture to post along with message

constructing an URL to use with HTTP post method.

Call HTTP post method. Do the success action id the call succeed else it end with “Error action”.

Drop your valuable comments in the Comment box.