Saturday, November 21, 2020

WP - post content image - keep aspect ratio

 class="wp-block-image "


.wp-block-image img{

max-width: 100%;

    height: auto;

}



or


.myclass  img{

max-width: 100%;

    height: auto;

}

WP Featured Image and Post Thumbnail

 


add in functions.php


add_theme_support( 'post-thumbnails' );

add_image_size('small-thumbnail', 350, 230, true);

add_image_size('post-image', 600, 400, true);



single.php

                  <?php the_post_thumbnail('post-image'); ?>




Monday, November 16, 2020

Wordpress Page contents display with if page id condition

Display some contents in certain pages of wordpress only.

Hide contents from some pages.


<?php  if(is_page(14))  {?>


display this.....

<?php  }   ?>

Sunday, November 15, 2020

Wordpress Post page designing with code

 Create file


single.php


Referance: https://wordpress.org/support/topic/create-new-basic-single-php-template/


<?php while ( have_posts() ) : the_post(); ?>



POST TITLE

<h1 class="intro-title mb-4"><h1 class="page-title"><a href="

<?php the_permalink(); ?>"><?php the_title();?>

</a></h1>



POST CONTENT

    <p>

        <?php the_content(); ?>

    </p>


<?php endwhile; ?>




Wednesday, November 11, 2020

Wp menu code - Navigation menu

 Activating navigation menu and using it with code.

function.php


add_theme_support('menus');

register_nav_menus(
    array(

        'primary-menu' => 'Primary Menu',
    )
)


<?php   echo get_home_url();  ?>


index.php

<?php 

$defaults = array( 

'container' => 'ul',

'theme_location' =>   'primary-menu',

'menu_class'  => 'nav navbar-nav '

);

wp_nav_menu( $defaults); 

?>



or


    $defaults = array
     'container' => 'ul',
     'theme_location' =>   'primary-menu',
     'menu_class'  => 'navbar-nav'
     );

     wp_nav_menu$defaults); 



Wordpress Home URL Button -- Php code

Home Button in Navigation menu of wordpress

 <li class="nav-item">
            <a class="nav-link js-scroll" 
                href="<?php   echo get_home_url();  ?>">Home</a>
 </li>

Wordpress page template -- landing page

 create new file


landing.php



<?php

/*
Template Name: Landing
*/
get_header(); 

?>

Tuesday, November 10, 2020

Boostrap to Wordpress Convertion notes

 Goto    wp-content/themes


create basic php and css files 




from   index.html

remove title,    copy from top to nav end  --- header.php

foooter to bottom --- footer.php


in between contents to  --- index.php


Functions.php


<?php

function b2w_theme_styles(){
    wp_enqueue_style("boostrap_css"get_template_directory_uri().'/lib/bootstrap/css/bootstrap.min.css');
    wp_enqueue_style("style_css"get_template_directory_uri().'/css/style.css');

}

add_action('wp_enqueue_scripts''b2w_theme_styles');

function b2w_theme_js{
    //wp_enqueue_script("jquery_js", get_template_directory_uri().'/lib/jquery/jquery.min.js');    
    wp_enqueue_script("migrate_js"get_template_directory_uri().'/lib/jquery/jquery-migrate.min.js'array('jquery'),'',true);    
    wp_enqueue_script("popper_js"get_template_directory_uri().'/lib/popper/popper.min.js'array('jquery'),'',true);
    wp_enqueue_script("boostrap_js"get_template_directory_uri().'/lib/bootstrap/js/bootstrap.min.js'array('jquery'),'',true);
 
}

add_action('wp_enqueue_scripts''b2w_theme_js');



?>


replace link src  top   --  header.php

<?php wp_head(); ?>


add in footer.php


  <?php  wp_footer(); ?>



add header, footer to index

 <?php  get_header(); ?>

  <?php  get_footer(); ?>




Make images work

<?php echo get_template_directory_uri(); ?>

style="background-image: url(<?php echo get_template_directory_uri(); ?>/img//intro-bg.jpg)"


Title, dec

<?php bloginfo('name'?>

reference



Post thumbnail feature-- for enabling portfolio like

In functions.php  add   --->  add_theme_support('post-thumbnails');

to enable featured image option





Nav Menu

add_theme_support('menus');







Friday, October 2, 2020

theme property for widget - floating action button

 floatingActionButton: Theme(

  data: ThemeData(accentColor: Colors.green),
child: FloatingActionButton(
child: Icon(Icons.add),
),
),

theme reference - bg color text color

 Widget build(BuildContext context) {

  return MaterialApp(
theme: ThemeData(
primaryColor: Color(0xFF0A0E21),
scaffoldBackgroundColor: Color(0xFF0AE21),
accentColor: Colors.purple,
textTheme: TextTheme(
body1: TextStyle(color: Color(0xFFFFFFFF)),
)),
home: InputPage(),
);

Monday, August 31, 2020

Flutter App: Card using Card Class, Padding, List Tile

 




Flutter App: Card using Container , Row Layout

Container, Row

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.teal,
body: SafeArea(
child: Column(
children: [
CircleAvatar(
radius: 50.0,
backgroundImage: AssetImage('images/sreeraj.jpg'),
),
Text(
'Sreeraj Melath',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 40.0,
color: Colors.white,
fontWeight: FontWeight.bold),
),
Text(
'FLUTTER DEVELOPER',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 20.0,
letterSpacing: 3,
color: Colors.teal[100],
fontWeight: FontWeight.bold),
),
Container(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
padding: EdgeInsets.all(10.0),
child: Row(
children: [
Icon(Icons.phone, color: Colors.teal[900]),
SizedBox(
width: 20.0,
),
Text(
"+91 9846 098 460",
style: TextStyle(
color: Colors.teal[900],
fontFamily: 'SourceSansPro',
fontSize: 20.0,
fontWeight: FontWeight.bold),
),
],
),
),
Container(
color: Colors.white,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
padding: EdgeInsets.all(10.0),
child: Row(
children: [
Icon(
Icons.email,
color: Colors.teal[900],
),
SizedBox(
width: 20.0,
),
Text(
"sreeraj@infoexpo.in",
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 20.0,
color: Colors.teal[900],
fontWeight: FontWeight.bold,
),
)
],
),
)
],
),
),
),
);
}
}

Flutter App : Layout Row , Widget Sections

 


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.teal,
body: SafeArea(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
width: 100,
color: Colors.red,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 100,
height: 100,
color: Colors.yellow,
),
Container(
width: 100,
height: 100,
color: Colors.green,
)
],
),
Container(
width: 100,
color: Colors.blue,
),
],
),
),
),
);
}
}

Saturday, August 29, 2020

Flutter App Code: Displaying Asset Image in folder

Right click project folder --> Create images folder --- copy paste the image

Add the asset to the pubspec.yaml


import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text("National Park"),
backgroundColor: Colors.blueGrey[900],
),
body: Center(
child: Image(image: AssetImage('images/bird.png')),
),
),
),
);
}


Flutter App : Displaying An image

 import 'package:flutter/material.dart';


void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text("My Image App"),
backgroundColor: Colors.blueGrey[900],
),
body: Center(
child: Image(
image: NetworkImage(
'https://images.squarespace-cdn.com/content/v1/5a5906400abd0406785519dd/1552662149940-G6MMFW3JC2J61UBPROJ5/ke17ZwdGBToddI8pDm48kLkXF2pIyv_F2eUT9F60jBl7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0iyqMbMesKd95J-X4EagrgU9L3Sa3U8cogeb0tjXbfawd0urKshkc5MgdBeJmALQKw/baelen.jpg'),
),
),
),
),
);
}

Flutter Hello World App Code

 


import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Center(
child: Text('Hello World'),
),
),
);
}

Sunday, August 16, 2020

Vanilla JS ToDo App - Codes

 mkdir vanilla-js-todo

cd vanilla-js-todo


Intalling touch (unix)

npm install touch-cli -g

touch index.html style.css app.js   



VS CODE :     !    to generate HTML snippet


header.logo + TAB key

link    - for style linking code


install live server extension


https://fonts.google.com/specimen/Raleway?query=ral&sidebar.open=true&selection.family=Raleway:ital,wght@0,300;1,300



font awesome cdn  - cdnjs.com


open index.html by right click - > open with live server




CSS  - click correction

i{
    pointer-eventsnone;
}


Monday, August 3, 2020

MERN STACK - Amazona Project Part #4 - User Login and Registration

Sign In route

router.post('/signin'async (reqres=> {

    const signinUser = await User.findOne({
        email: req.body.email,
        password: req.body.password
    });
   
});
if(signinUser){
    res.send({
        _id: signinUser.id,
        name: signinUser.name,
        email:signinUser.email,
        isAdmin: signinUser.isAdmin,
        token: getToken(user)
    })
else {
    res.status(401).send({msg: 'Invalid Email or Password.'});
}


npm install jsonwebtoken


Create util.js  in backend folder

import jwt from 'jsonwebtoken';
import config from './config';

const getToken = (user=> {
    return jwt.sign(userconfig.JWT_SECRET, {
        expiresIn: '48h'
    })
}

export{
    getToken
}




Create signIn screen






Create userActions.js

Create userReducer.js



npm install body-parser

middle ware for express - provides post data sent by user to the node app







Create RegisterScreen.js







Sunday, August 2, 2020

MERN STACK - Amazona Project Part 3

Multiple items in cart need to be saved in cookies


Cookies setup 


npm install js-cookie

in frontent folder


import Cookie from "js-cookie";

---
const removerFromCart = (productId) => (dispatch, getState) => {
    dispatch({ type: CART_REMOVE_ITEM, payload:productId });

    const { cart: {cartItems } }  = getState();
    Cookie.set("cartItems", JSON.stringify(cartItems));

}

store.js



const cartItems = Cookie.getJSON("cartItems") || [];

const initialState = { cart : {cartItems} };



 


Mongo DB setup



create .env file in the root amazona

MONGODB_URL=mongodb://localhost/amazona

npm install dotenv

Create config.js inside amazon/backend/ 
export default {
    MONGODB_URL: process.env.MONGODB_URL || 'mongodb://localhost/amazona'
}
Add  to server.js

import dotenv from 'dotenv';
import config from './config';

dotenv.config();


Download and install MONGO DB  


Install mongoose  @amazona root

npm install mongoose

Add in server.js 

const mongodbUrl = config.MONGODB_URL;
mongoose.connect(mongodbUrl, {
    useNewUrlParser:true;
}).catch(error => console.log(error.reason));



Create Models/userModel.js in backend


import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
    name: { type: Stringrequired:true },
    email: { type: Stringrequired: trueunique:true },
    password: { type: Stringrequired:true },
    isAdmin: { type:Booleanrequireddefault: false }
});

const userModel = mongoose.model("User"userSchema);

export default userModel;



Create Routes/userRoute.js  in backend


import express from 'express';
import User from '../models/userModel';

const router = express.Router();

router.get("/api/users/createadmin"async(reqres=> {
    
    try {
        const user = new User({
            name: 'Sreeraj',
            email: 'sreeraj@infoexpo.in',
            password:'12345',
            isAdmin: true
    
        });
        const newUser = await user.save();
        res.send(newUser);
    } catch (error) {
        res.send({ msg: error.message });
    }

});










Thursday, July 30, 2020

VS Code Shortcuts

Commonly usable and helpful VS code editor software shortcuts for programmers.



Find and Open File with file name    :    Ctrl + P

Tuesday, July 28, 2020

Server Side Steps - Ecommerce project - Node JS steps - Using Express JS


  • Create folder - Amazona/backend 

  • Create file server.js


Run npm init in the root folder(amazona)



  • Install Express JS  

npm install express    (root folder)

  • Run the backend

node backend/server.js
error:   code written in ES6 , node only understands es5   --- convert it

ES6 Conversion

npm install @babel/cli @babel/core @babel/node @babel/preset-env nodemon

npm install @babel/cli @babel/core @babel/node @babel/preset-env nodemon --save-dev


Create .babelrc file in the root with below code

{
    "presets": [
        [
            "@babel/preset-env"
        ]
    ]
}


edit package.json

  "scripts": {
    "start""nodemon --watch backend --exec babel-node backend/server.js"
  },



RUN backend using : 

npm start


we can get the json data printed 



Use react hooks to get data from the server

  • create proxy inside the frontent folder

package.json  - add the proxy code


  "name""frontend",
  "proxy""http://127.0.0.1:5000", // add this line
  "version""0.1.0",
 




Go to frontent  - install axios

npm install axios

    const [productssetProduct] = useState([]);

    useEffect(()  => {
      const fetchData = async () =>{
        const {data} = await axios.get("/api/products");
        setProduct(data);
      }
      fetchData();
      return () => {
        //
      };
    }, [])   




trouble shoot network requests


Developer Tools --- Network ---- XHR


State Management using REDUX


Go to /frontent/
npm install redux react-redux






create store with product reducers


  • Wrap the <App /> in index js with
 

const store = createStore(reducerinitialStatecompose(applyMiddleware(thunk)));

//thunk is a redux middleware allows to run async operation in the action in redux


npm install redux-thunk


Add redux tool to dev tools


const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSTION_COMPOSE__ || compose;

  • define constants  -- create constants folder



---- useSelector

 create :   actions ---> productActions.js

redux state , move axios code

   
 return loading ? <div> Loading...</div>:
      error ? <div>{error}</div>:
    <ul className="products">

 




Redux to Product Details Page



Create web api  --- for individual product details



create constansts
create reducers
add to store


Add to Cart & Qty

const [qty, setQty] = useState(1);

                         <li> 
                            Qty: <select value={qty} onChange={(e) => { setQty(e.target.value)} } >
                               {[...Array(product.countInStock).keys()].map(x=>
                                <option key={x+1} value={x+1}>{x+1}</option>
                                )}
                            </select>
                        </li>


Monday, July 27, 2020

HTML to React App -- Convertion Steps

  • Create React App
npx create-react-app app-name


cd  app-name


npm start

Steps of conversion
  • Copy paste css to index.css
  • Copy paste contents inside <body> to App.js  return data
  • Replace "class" with "className"    (since class is a reserved keyword and cannot be used inside the js file)
  • Create images folder inside public then move images to that
  • rename images path   to   /images/name.jpg


Define functions

  const openMenu = () => {
    document.querySelector(".sidebar").classNameList.add("open");
  }
  const closeMenu = () => {
    document.querySelector(".sidebar").classNameList.remove("open");
  }



function call

replace  onclick="closeMenu()" to onClick={closeMenu}


Change onclick to onClick


Add  transition: all .5s;   to css



static to dynamic product list - JSX

<ul className="products">

              {
                data.products.map(product => 
                  <li>
                    <div className="product">
                          <img className="product-image" src={product.image} alt="product" />
                          <div className="product-name"> 
                              <a href="product.html">{product.name}</a>
                          </div>
                          <div className="product-brand">{product.brand}</div>
                          <div className="price"> ${product.price}</div>
                          <div className="product-rating"> {product.rating} Stars ({product.reviewCount} reviews)</div>
                      </div>
                  </li>                
                )
              }
                
            </ul>



Routing in React

npm install react-router-dom


Wrap the return contents in <BrowserRouter> </BrowserRouter>

import { BrowserRouterRoute } from 'react-router-dom';


  • Product page

#root{ height: 100%; }



  • Change the link code / replace <a> with <Link>

<Link to="/"> Amazon Store </Link>

<a href="index.html"> Amazon Store</a>

import {Link} from 'react-router-dom';