article

Showing posts with label WordPress. Show all posts
Showing posts with label WordPress. Show all posts

Thursday, November 21, 2024

React.js + WordPress Load Posts with Featured Image and View Single Page | Tailwind CSS

React.js + WordPress Load Posts with Featured Image and View Single Page | Tailwind CSS

React JS https://react.dev/learn/start-a-new-react-project npx create-next-app@latest npx create-react-app@latest {project name} Create Project C:\react-js>npx create-react-app@latest my-app Run C:\react-js\my-app> npm start Install tailwindcss https://tailwindcss.com/docs/guides/create-react-app npm install -D tailwindcss npx tailwindcss init Install react-router-dom https://www.npmjs.com/package/react-router-dom Install axios src\App.js
//src\App.js 
import { BrowserRouter, Routes, Route } from "react-router-dom"; //npm i react-router-dom https://www.npmjs.com/package/react-router-dom
import Home from "./elements/Home";
import ViewPage from "./elements/ViewPage";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/posts/:slug" element={<ViewPage />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;
src\elements\Home.js
//src\elements\Home.js
import React  from 'react';
import Posts from './Posts'
import { Suspense } from "react";
import { IoSearch } from "react-icons/io5"; //https://www.npmjs.com/package/react-icons npm install react-icons --save

function Home() {

  return (
    <div className="w-screen py-20 flex justify-center flex-col items-center">
        <div className="flex items-center justify-between gap-1 mb-5">
            <h1 className="text-4xl font-bold">React.js + WordPress Load Posts with Featured Image and View Single Page | Tailwind CSS</h1>
        </div> 
        <div className="overflow-x-auto py-10">
            <div className="mb-2 w-full text-right">
                <div className="relative flex flex-1">
                <input
                    type="text"
                    className="w-full border border-gray-200 py-2 pl-10 text-sm outline-2 rounded-sm"
                    placeholder="Search..."
                />
                <IoSearch className="absolute left-3 top-2 h-5 w-5 text-gray-500" />
                </div>
            </div>
            <Suspense fallback="Loading...">
                <Posts/>
            </Suspense>
        </div>
    </div>
  )
}

export default Home
src\elements\Posts.js
//src\elements\Posts.js
import React, { useEffect, useState } from 'react';

export default function Posts() {
    const [posts, setPosts] = useState([]);
    useEffect(() => {
        async function loadPosts() {
            const response = await fetch('http://localhost:8888/cairocoders/wp-json/wp/v2/posts?_embed');
            if(!response.ok) {
                // oups! something went wrong
                return;
            }
    
            const posts = await response.json();
            setPosts(posts);
        }
    
        loadPosts();
   }, [])
  return (
      <div className="grid md:grid-cols-3 gap-5 mt-10">
        {posts.map((post, index) => (
          <div key={index} className="max-w-sm border border-gray-200 rounded-md shadow">
            <div className="relative aspect-video">
              <img src={post._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url}
                alt={post.title.rendered}
                fill
                priority
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                className="rounded-t-md object-cover"/>
            </div>
            <div className="p-5">
              <h1>
                <a
                  href={`/posts/${post.slug}`}>
                  {post.title.rendered}
                </a>         
              </h1>
            </div>
          </div>
        ))}
      </div>
 );
}
src\elements\ViewPage.js
//src\elements\ViewPage.js
import React from 'react';
import { useEffect, useState } from 'react';
import { useParams } from "react-router-dom"; 

export default function Posts() {
    const {slug}=useParams();

    const [posts, setData] = useState(null);

    useEffect(()=>{
        fetchPost();
    },[slug]);
     
    const fetchPost=async()=>{
        try{
          const response = await fetch("http://localhost:8888/cairocoders/wp-json/wp/v2/posts?_embed&slug="+slug);
            if(!response.ok) {
                // oups! something went wrong
                return;
            }

            const posts = await response.json();
            //console.log(posts);
            setData(posts);
        }catch(err){
            console.log("Something Wrong");
        }
    }

    return (
    <div className="min-h-screen flex items-center justify-center bg-slate-100">
      <div className="bg-white rounded-sm shadow p-8">
        {posts && posts.map((post, index) => (
        <div key={index}>
          <h1 className="text-2xl font-bold mb-5">{post.title.rendered}</h1>
            <div className="mb-4">            
              <div 
                dangerouslySetInnerHTML={{ __html: post['content']['rendered'] }}
              />   
            </div>
        </div>
        ))}
     </div>
    </div>
  );
}
themes\cairocoders\functions.php
//themes\cairocoders\functions.php
<?php
/**
 * Theme functions and definitions
 *
 * @package cairocoders
 */

add_action('rest_api_init', 'register_rest_images' );

function register_rest_images(){
    register_rest_field( array('post'),
        'fimg_url',
        array(
            'get_callback'    => 'get_rest_featured_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

function get_rest_featured_image( $object, $field_name, $request ) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
        return $img[0];
    }
    return false;
}
Run C:\react-j\my-app>npm start
http://localhost:3000/

Wednesday, November 13, 2024

Nextjs + WordPress Load Posts with Featured Image and View Single Page

Nextjs + WordPress Load Posts with Featured Image and View Single Page

app\posts\page.tsx
//app\posts\page.tsx
import { Suspense } from "react";
import { Spinner } from "@/components/spinner";
import PostTable from "@/components/tableposts";

const Posts = async () => {

  return (
    <div className="max-w-screen-lg mx-auto py-14">
      <h1 className="text-4xl font-bold">Nextjs + WordPress Load Posts with Featured Image and View Single Page</h1>
      <div className="flex items-end justify-between m-12">
        <h1 className="text-4xl font-bold">Latest Post</h1>
      </div>

      <Suspense fallback={<Spinner />}>
        <PostTable/>
      </Suspense>

    </div>
  );
};

export default Posts;
app\components\tableposts.tsx
//app\components\tableposts.tsx
import Image from "next/image";
import Link from "next/link";
import { formatDate } from "@/lib/utils";

const PostTable = async () => {
  const res = await fetch("http://localhost:8888/cairocoders/wp-json/wp/v2/posts?_embed");
  const data = await res.json();

  return (
      <div className="grid md:grid-cols-3 gap-5 mt-10">
        {data.map((post: any) => (
          <div key={post.id} className="max-w-sm border border-gray-200 rounded-md shadow">
            <div className="relative aspect-video">
              <Image
                src={post._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url}
                alt={post.title.rendered}
                fill
                priority
                sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                className="rounded-t-md object-cover"
              />
            </div>
            <div className="p-5">
              <h1>
                <Link href={`/posts/${post.slug}`}>{post.title.rendered}</Link>
              </h1>
            </div>
            <div className="flex items-center justify-between">
              <div className="py-3 text-sm text-black rounded-bl-md w-full text-center">{formatDate(post.date.toString())}</div>
            </div>
          </div>
        ))}
      </div>
  );
};

export default PostTable;
app\components\Spinner.tsx
//app\components\Spinner.tsx
export const Spinner = () => {
  return (
    <span className="loading loading-spinner loading-lg">Loading</span>
  );
};
app\posts\[slug]\page.tsx
//app\posts\[slug]\page.tsx
import { notFound } from "next/navigation";
 
const PostPage = async ({ params }: { params: { slug: string } }) => {
  const slug = params.slug;
  //console.log(data);

  const res = await fetch(`http://localhost:8888/cairocoders/wp-json/wp/v2/posts?_embed&slug=${slug}`);
  const data = await res.json();

  if (!data) return notFound();
 
  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-100">
      <div className="bg-white rounded-sm shadow p-8">
        {data.map((post) => (
          <div key={post.id}>
            <h1 className="text-2xl font-bold mb-5">{post.title.rendered}</h1>
            <div className="mb-4">            
              <div 
                dangerouslySetInnerHTML={{ __html: post['content']['rendered'] }}
              />   
            </div>
          </div>
        ))}

      </div>
    </div>
  );
};
 
export default PostPage;
next.config.mjs
//next.config.mjs
/** @type {import('next').NextConfig} */
//const nextConfig = {};
const nextConfig = {
  reactStrictMode: true,
  images : {
    domains : ['localhost'] // Domain name
  }
}

export default nextConfig;
themes\cairocoders\functions.php
//themes\cairocoders\functions.php
<?php
/**
 * Theme functions and definitions
 *
 * @package cairocoders
 */

add_action('rest_api_init', 'register_rest_images' );

function register_rest_images(){
    register_rest_field( array('post'),
        'fimg_url',
        array(
            'get_callback'    => 'get_rest_featured_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

function get_rest_featured_image( $object, $field_name, $request ) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
        return $img[0];
    }
    return false;
}
run C:\nextjs>npm run dev

Tuesday, February 19, 2019

How to create wordpres plugins custom admin menu

How to create wordpres plugins custom admin menu

1. first create folder wp-content\plugins\admin_menu
2. create php file admin.php

Code
<?php
/**
* Plugin Name: Admin Menu
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom admin menu.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
function theme_options_panel(){
  add_menu_page('Theme page title', 'Theme menu', 'manage_options', 'theme-options', 'wps_theme_func');
  add_submenu_page('theme-options', 'Settings page title', 'Settings menu label', 'manage_options', 'theme-op-settings', 'wps_theme_func_settings');
  add_submenu_page('theme-options', 'FAQ page title', 'FAQ menu label', 'manage_options', 'theme-op-faq', 'wps_theme_func_faq');
}
add_action('admin_menu', 'theme_options_panel');
//function
function wps_theme_func(){
        echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
        <h2>Theme</h2></div>';
}
function wps_theme_func_settings(){
        echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
        <h2>Settings</h2></div>';
}
function wps_theme_func_faq(){
        echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
        <h2>FAQ</h2></div>';
}

Tuesday, February 5, 2019

How to create WordPress plugins with Shortcode Ajax

How to create WordPress plugins with Shortcode Ajax

1. Create folder name wp-content\plugins\"myplugins_shortcode_ajax"
2. Add index.php file wp-content\plugins\myplugins_shortcode_ajax\index.php
3. Add code index.php
//index.php
<?php
/**
* Plugin Name: Shortcode ajax
* Plugin URI: https://tutorial101.blogspot.com/
* Description: How to add a form to a shortcode in WordPress (using PHP and Ajax)
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
$ajaxpostExample = new ajaxpostExample(); 
class ajaxpostExample {
 public function __construct() {
        $this->attach_actions();
  $this->attach_shortcodes();
    }
 function attach_actions() {
        add_action('wp_ajax_nopriv_ajax_do_something', array($this, 'do_something_serverside'));
        add_action('wp_ajax_ajax_do_something', array($this, 'do_something_serverside')); /* notice green_do_something appended to action name of wp_ajax_ */
        add_action('wp_enqueue_scripts', array($this, 'theme_enqueue_styles'), 99999);
    }
 function theme_enqueue_styles() {
        //include the js
  wp_enqueue_script('ajaxsample_script', plugin_dir_url(__FILE__) . 'js/ajax_call_to_handle_form_submit.js', array('jquery'));
  wp_enqueue_style('handlecss',  plugin_dir_url(__FILE__) . 'css/ajaxshortcodestyle.css');
  // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
  // Register the script
  //wp_localize_script( $handle, $name, $data );
  wp_localize_script('ajaxsample_script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'we_value' => 1234));
 }
 function do_something_serverside() {
  global $wpdb;
  // output to ajax call   
  $txtname = $_POST['txtname'];
  $txtemail = $_POST['txtemail'];
  $txtsubject = $_POST['txtsubject'];
  $txtmessage = $_POST['txtmessage'];
  if ($txtname=='' OR $txtemail==''){
   echo "false"; 
  }else{ 
   echo "true";
  }
  //insert to a custom database table
  $wpdb->insert("test", array(
   "contactname" => $txtname
  ));
        die();
    }
 function attach_shortcodes() {
        add_shortcode('shortcode_ajax_form', array($this, 'shortcode_with_form_code')); //<p>[shortcode_ajax_form]</p>
    }
    function shortcode_with_form_code($atts, $content = null) {
        if ($this->formOk()) {
            return " <div>thanks your form has been submitted</div>";
        } else {
            return $this->show_form();
        }
    }
 function show_form() {
        $form = '<div class="well"><div id="display_rec"></div>
        <form id="green_form" action="">
          Name:<br>
          <input type="text" name="txtname" class="form-control" value="">
          <br>
          Email Address:<br>
          <input type="text" name="txtemail" class="form-control" value="">
    <br>
          Subject:<br>
          <input type="text" name="txtsubject" class="form-control" value="">
    <br>
          Message:<br>
          <textarea name="txtmessage" class="form-control" rows="5" cols="25" required="required" placeholder="Message"></textarea>
          <br>
          <br>
          <input type="submit" class="btn-primary" value="Submit" >
        </form></div>';
        return $form;
    }
 function formOk(){
        return false; 
    }
} 
4. Create folder name for js file wp-content\plugins\myplugins_shortcode_ajax\js\ajax_call_to_handle_form_submit.js then add this code
jQuery( document ).ready(function() {
    // Handler for .ready() called.
    //
    jQuery(function(){
  jQuery("#green_form").submit(function(event){
   event.preventDefault();
            var formOk = true;
            // do js validation 
   jQuery.ajax({
    url:ajax_object.ajax_url,
                type:'POST',
                data: jQuery(this).serialize() + "&action=ajax_do_something", //wp_ajax_nopriv_ajax_do_something, wp_ajax_ajax_do_something
    success:function(response){ 
     if(response=="true"){
                       //alert('success'); 
        jQuery("#display_rec").html("<div class='success'><p>Message Success Sent</p></div>")
                    }else{
                        jQuery("#display_rec").html("<div class='fail'>Please input required fields.</div>")
                        //alert('Please input required fields.'); 
                    } 
                }
   });
  }); 
    });
});
5. css code wp-content\plugins\myplugins_shortcode_ajax\css\ajaxshortcodestyle.css
.form-control {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
.btn-primary {
    color: #fff;
    background-color: #428bca;
    border-color: #357ebd;
}
.well {
    padding: 19px;
    margin-bottom: 20px;
    background-color: #428bca;
    border: 1px solid #357ebd;color:#fff;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
}
.success, .fail, .information, .attention {
 background-repeat: no-repeat;
 background-position: 10px center;
 height: 40px;
 font-size: 11px;
 line-height: 22px;
 margin-bottom: 20px;
 padding-top: 10px;
 padding-right: 10px;
 padding-bottom: 10px;
 padding-left: 50px;
 
}
/* Succes Notification Box */
.success     {
 background-color: #EBF8D6;
 border: 1px solid #A6DD88;
 color: #539B2D;
 background-image: url(../images/accept00.png);
}
/* Failure Notification Box */
.fail      {
 background-color: #FFECE6;
 border: 1px solid #FF936F;
 color: #842100;
 background-image: url(../images/delete00.png);
}
/* Information Notification Box */
.information    {
 background-color: #D3EEF1;
 border: 1px solid #81CDD8;
 color: #369CAB;
 background-image: url(../images/info0000.png);
}
/* Attention Notification Box */
.attention   {
 background-color: #FFFBCC;
 border: 1px solid #FFF35E;
 color: #C69E00;
 background-image: url(../images/warning0.png);
}
6. Shortcode [shortcode_ajax_form]

Monday, February 4, 2019

How to create wodpress plugins and shortcodes 11 example from simple to complex

How to create wodpress plugins and shortcodes 11 example from simple to complex

List of tutorial
1. How to create contact form with submit mail
2. How to insert record post database table
3. How to insert shortcode google ads
4. How to list recent post
5. How to list recent post in shortcode parameters
6. How to list recent post in content shortcode
7. How to enabling shortcodes in widgets
8. Display wordpress menu in shortcode
9. How to insert A Google Maps shortcode
10. How to embed pdf
11. How to Displaying database table data in shortcodes

A standard header is introduced below to establish your plugin’s presence.
<?php
/**
* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12
*/
Create folder under plugins folder wp-content\plugins\myplugins_with_shortcode folder name myplugins_with_shortcode and create php file index.php file
2. Add the code below wp-content\plugins\myplugins_with_shortcode\index.php
<?php
/**
* Plugin Name: Custom Plugins with shortcode
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom plugin and shortcode for example.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
//first example how to create contact form with submit mail
function form_creation(){
 //add submit 
 if (isset( $_POST['cmdsubmit'])) {
        $txtname = $_POST['txtname'];
        $txtemail = $_POST['txtemail'];
        $message = $_POST['message'];
  $msg = "Name: $txtname <br/>Email: $txtemail <br/>Message: $message <br/>";
    // send email
  mail("someone@example.com","My subject",$msg);
    }
 $form .= '<div class="well"><p><h5>Simple Contact Form</h5></p><form method = "post">
 Name: <input type="text" name="txtname" class="form-control"><br>
 Email: <input type="email" name="txtemail" class="form-control"><br>
 Message: <textarea name="message" class="form-control"> Enter text here…</textarea><br/>
 <input type="submit" name="cmdsubmit"> '.$msg.'
 </form></div>';
 return "$form";
}
add_shortcode("testform", "form_creation"); //add code //<p>[testform]</p>
//add css file
function wpse_89494_enqueue_scripts() {
 wp_enqueue_style('handlecss',  plugin_dir_url(__FILE__) . 'css/ajaxshortcodestyle.css');
}
//second example how to insert to post
function input_fields( $atts ) {
 //add submit
 if ( isset( $_POST['gg'] ) ) {
        $post = array(
            'post_content' => $_POST['content'], 
   'post_status' => 'publish',
            'post_title'   => $_POST['title']
        );
  // Insert the post into the database
        wp_insert_post($post); //https://developer.wordpress.org/reference/functions/wp_insert_post/
    }
    $formpost .= '<form method = "post">
        Post title : <input type="text" name="title"><br/>
        Post Contents : <input type="text" name="content"></br/>
        <input type="submit" name="gg">
    </form>';
 return "$formpost";
}
add_shortcode( 'add_fields', 'input_fields' );
//third example shortcode google ads
function get_adsense($atts) {
    return '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- WordPress hosting -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-0327511395451286"
     data-ad-slot="6566424785"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
}
add_shortcode('adsense', 'get_adsense');
//4th example how to list recent post
function recent_posts_function() {
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
      endwhile;
   endif;
   wp_reset_query();
   return $return_string;
}
add_shortcode('recent_posts', 'recent_posts_function');
//5 example SHORTCODE PARAMETERS
function recent_posts_function2($atts){
   extract(shortcode_atts(array(
      'posts' => 1,
   ), $atts));
   $return_string = '<ul>';
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
   endif;
   $return_string .= '</ul>';
   wp_reset_query();
   return $return_string;
}
add_shortcode('recent_posts2', 'recent_posts_function2'); 
//6 example CONTENT IN SHORTCODE [recent-posts posts="5"]This is the list heading[/recent-posts]
function recent_posts_function3($atts, $content = null) {
   extract(shortcode_atts(array(
      'posts' => 1,
   ), $atts));
   $return_string = '<h3>'.$content.'</h3>';
   $return_string .= '<ul>';
   query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
   if (have_posts()) :
      while (have_posts()) : the_post();
         $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      endwhile;
   endif;
   $return_string .= '</ul>';
   wp_reset_query();
   return $return_string;
}
add_shortcode('recent_posts3', 'recent_posts_function3');
//7 example ENABLING SHORTCODES IN WIDGETS
add_filter('widget_text', 'do_shortcode');

//8 example WORDPRESS MENU
function menu_function($atts, $content = null) {
   extract(
      shortcode_atts(
         array( 'name' => null, ),
         $atts
      )
   );
   return wp_nav_menu(
      array(
          'menu' => $name,
          'echo' => false
          )
   );
}
add_shortcode('menu', 'menu_function');
//9 example A Google Maps shortcode
function googlemap_function($atts, $content = null) {
   extract(shortcode_atts(array(
      "width" => '640',
      "height" => '480',
      "src" => ’
   ), $atts));
   return '<iframe width="'.$width.'" height="'.$height.'" src="'.$src.'&output=embed" ></iframe>';
}
add_shortcode("googlemap", "googlemap_function");

//10 example PDF EMBEDDING
function pdf_function($attr, $url) {
   extract(shortcode_atts(array(
       'width' => '640',
       'height' => '480'
   ), $attr));
   return '<iframe src="http://docs.google.com/viewer?url=' . $url . '&embedded=true" style="width:' .$width. '; height:' .$height. ';">Your browser does not support iframes</iframe>';
}
add_shortcode('pdf', 'pdf_function'); 
// last 11 example Displaying database table data in shortcodes
function listpost_func()
{
 global $wpdb;
    $postshow .= '<div class="recent-posts">';
 $sql_post = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status='publish'");
 foreach ($sql_post as $rows_post) 
 {
  $post_title = $rows_post->post_title;  
   $postshow .= '<h6>'.$post_title.'</h6>';
 }
    $postshow .= '</div>';
 return "$postshow";
}
add_shortcode( 'listpost', 'listpost_func' ); 
css code wp-content\plugins\myplugins_with_shortcode\css\ajaxshortcodestyle.css
.form-control {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
.btn-primary {
    color: #fff;
    background-color: #428bca;
    border-color: #357ebd;
}
.well {
    padding: 19px;
    margin-bottom: 20px;
    background-color: #428bca;
    border: 1px solid #357ebd;color:#fff;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.05);
}

Thursday, January 31, 2019

How To Create A WordPress Plugin

How To Create A WordPress Plugin

A plugin must contain a bit of meta information which tells WordPress what it is and how to handle it within your website.

A standard header is introduced below to establish your plugin’s presence.



<?php
/**
* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12
*/

1 Create folder under plugins folder  wp-content\plugins\myplugins folder name myplugins and create index.php file

2. Add the code below

<?php
/**
* Plugin Name: Custom Music Reviews
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom music review plugin built for example.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/

// Register the Custom Music Review Post Type
function register_cpt_music_review() {
    $labels = array(
        'name' => _x( 'Music Reviews', 'music_review' ), //post type is called music_review url https://codex.wordpress.org/Post_Types
        'singular_name' => _x( 'Music Review', 'music_review' ), 
        'add_new' => _x( 'Add New', 'music_review' ), //and new link wp-admin/post-new.php?post_type=music_review
        'add_new_item' => _x( 'Add New Music Review', 'music_review' ),
        'edit_item' => _x( 'Edit Music Review', 'music_review' ),
        'new_item' => _x( 'New Music Review', 'music_review' ),
        'view_item' => _x( 'View Music Review', 'music_review' ),
        'search_items' => _x( 'Search Music Reviews', 'music_review' ),
        'not_found' => _x( 'No music reviews found', 'music_review' ),
        'not_found_in_trash' => _x( 'No music reviews found in Trash', 'music_review' ),
        'parent_item_colon' => _x( 'Parent Music Review:', 'music_review' ),
        'menu_name' => _x( 'Music Reviews', 'music_review' ), //left side menu edit.php?post_type=music_review
    );
 
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'Music reviews filterable by genre',
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ),
        'taxonomies' => array( 'genres' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-format-audio',
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );
 
    register_post_type( 'music_review', $args );
} 
add_action( 'init', 'register_cpt_music_review' );

//custom taxonomies to extend themes or plugins 
//Register a new Taxonomy using register_taxonomy() 
function genres_taxonomy() { //taxonomy is a way to group things together.
    register_taxonomy( //https://codex.wordpress.org/Taxonomies
        'genres', //new taxonomy called genres
        'music_review', //and assigns it to our post type music_review
        array(
            'hierarchical' => true,
            'label' => 'Genres', //edit-tags.php?taxonomy=genres&post_type=music_review
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'genre',
                'with_front' => false
            )
        )
    );
}
add_action( 'init', 'genres_taxonomy');


// Function used to automatically create Music Reviews page.
function create_music_review_pages()
  {
   //post status and options
    $post = array(
          'comment_status' => 'open',
          'ping_status' =>  'closed' ,
          'post_date' => date('Y-m-d H:i:s'),
          'post_name' => 'music_review',
          'post_status' => 'publish' ,
          'post_title' => 'Music Reviews',
          'post_type' => 'page',
    );
    //insert page and save the id
    $newvalue = wp_insert_post( $post, false );
    //save the id in the database
    update_option( 'mrpage', $newvalue );
  }
// Activates function if plugin is activated
register_activation_hook( __FILE__, 'create_music_review_pages');

//Testing
//first create a new page called "Music Reviews" http://localhost/wordpress/music_review/
//Lets create an example music review and see what outputs.

Sunday, January 14, 2018

How to Add Widgets to WordPress Theme’s Footer

How to Add Widgets to WordPress Theme’s Footer

1. Register the footer widget area

Open the functions.php file from the WordPress Theme Editor and search for the following line of code:


register_sidebar

Add the following block of code just below the other sidebar registration code

function twentysixteen_widgets_init() {
 register_sidebar( array(
  'name'          => __( 'Sidebar', 'twentysixteen' ),
  'id'            => 'sidebar-1',
  'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) );

 register_sidebar( array(
  'name'          => __( 'Content Bottom 1', 'twentysixteen' ),
  'id'            => 'sidebar-2',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) );

 register_sidebar( array(
  'name'          => __( 'Content Bottom 2', 'twentysixteen' ),
  'id'            => 'sidebar-3',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) ); 
 register_sidebar( array(
  'name'          => __( 'Content Bottom 3', 'twentysixteen' ),
  'id'            => 'sidebar-4',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) ); 
}
add_action( 'widgets_init', 'twentysixteen_widgets_init' );


2. Show the footer widget area in your theme

Open your footer.php file and insert the following block of code where you want to show the footer widgets (this will show the 3 footer widget areas):

<div id="footer-sidebar" class="secondary">
<div id="footer-sidebar1">
 <?php
  if(is_active_sidebar('sidebar-2')){
  dynamic_sidebar('sidebar-2');
  }
 ?>
</div>
<div id="footer-sidebar2">
 <?php
 if(is_active_sidebar('sidebar-3')){
 dynamic_sidebar('sidebar-3');
 }
 ?>
</div>
<div id="footer-sidebar3">
 <?php
 if(is_active_sidebar('sidebar-4')){
 dynamic_sidebar('sidebar-4');
 }
 ?>
</div>
</div>

wp_nav_menu change sub-menu class name?

wp_nav_menu change sub-menu class name?

from <ul class="sub-menu"> to <ul class="dropdown-menu">

You can use WordPress preg_replace filter (in your theme functions.php file) example:

function new_submenu_class($menu) {    
    $menu = preg_replace('/ class="sub-menu"/',' class="dropdown-menu" ',$menu);        
    return $menu;      
}
add_filter('wp_nav_menu','new_submenu_class'); 

Monday, May 1, 2017

Create Custom Shortcode in WordPress Post, Page and Plugin

Create Custom Shortcode in WordPress Post, Page and Plugin

Edit current theme's function.php add this code


function recent_posts_func( $atts, $content = NULL ){
    $content = $content?$content:'Latest Posts';
    $a = shortcode_atts(
        array(
            'posts'=>5
        ),
        $atts
    );
    $args = array('numberposts'=>$a['posts']);
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
    echo '<div class="recent-posts">';
    echo '<h1>'.$content.'</h1>';
    foreach($recent_posts as $post){
    ?>
    <div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><span>Show Details</span>.</a></p></div>
    <?php
    }
    echo '</div>';
}
add_shortcode( 'latestposts', 'recent_posts_func' );

Shortcode content view:

Insert the shortcode through the WordPress admin panel editor, use the below code.

[latestposts posts="2"]Recent Posts[/latestposts]

Sunday, April 30, 2017

WordPress – Adding custom fields to the post

WordPress – Adding custom fields to the post

This extra custom fields data is known as meta-data. Meta data allow you to add some additional data to the post.

Edit current theme's functions.php below code 
/*
* Add the Custom Meta Box
*/

function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Custom Meta Box', // $title 
        'show_custom_meta_box', // $callback
        'post', // $page
        'normal', // $context
        'high' // $priority
    ); 
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// Custom meta fields array
$prefix = 'custom_';
$custom_meta_fields = array(
    array(
        'label'=> 'Author Name',
        'desc'  => 'Enter post author name to be displayed',
        'id'    => $prefix.'author_name',
        'type'  => 'text',
    ),
 array(
  'label'=> 'Photo',
        'desc'  => 'Enter url author photo',
        'id'    => $prefix.'photo_author',
        'type'  => 'text'
    )
);

// The callback function
function show_custom_meta_box() {

    global $custom_meta_fields, $post;
    
    // Use nonce for verification
    echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
     
    // Begin the field table and loop
    echo '<table class="form-table">';
    
    foreach ($custom_meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '<tr>
                <th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
                <td>';
                switch($field['type']) {
                    // text field
                    case 'text':
                        echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
                            <br /><span class="description">'.$field['desc'].'</span>';
                    break;
nbsp;               }
        echo '</td></tr>';
    }
    
    echo '</table>';
    
}

// Save the custom meta data
function save_custom_meta($post_id) {

    global $custom_meta_fields;
     
    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) 
        return $post_id;
        
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
        
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }
     
    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}
add_action('save_post', 'save_custom_meta');

Go to the post adding page and you can see the custom meta box and custom post fields under the post content editor.

Display the Custom Field Value

Edit current theme's single.php and add this code below


<?php 
    // Get the post meta data
    $meta = get_post_meta( get_the_ID() );
    
    // Get custom meta value
    $post_author_name = $meta['custom_author_name'][0];
    $post_photo_author = $meta['custom_photo_author'][0];
?>
<p>Author: <?php echo $post_author_name; ?> </p>
<p>Photo: <img src="<?php echo $post_photo_author; ?>"/> </p>

How to Create a Custom WordPress Widget

How to Create a Custom WordPress Widget

Add this code to your themes or functions.php
<?php
// Creating the widget 
class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget', 

// Widget name will appear in UI
__('Simple Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Simple widget', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
echo __( 'Hello, World!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
  
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
 
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here

// Register and load the widget
function wpb_load_widget() {
 register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

Friday, January 13, 2017

Wordpress Remove Menu admin page

Wordpress Remove Menu admin page

locate wp-admin\includes\plugin.php then add this code
function remove_menus(){
  remove_menu_page( 'index.php' );                  //Dashboard
  remove_menu_page( 'jetpack' );                    //Jetpack* 
  remove_menu_page( 'edit.php' );                   //Posts
  remove_menu_page( 'upload.php' );                 //Media
  remove_menu_page( 'edit.php?post_type=page' );    //Pages
  remove_menu_page( 'edit-comments.php' );          //Comments
  remove_menu_page( 'themes.php' );                 //Appearance
  remove_menu_page( 'plugins.php' );                //Plugins
  remove_menu_page( 'users.php' );                  //Users
  remove_menu_page( 'tools.php' );                  //Tools
  remove_menu_page( 'options-general.php' );        //Settings
}
add_action( 'admin_menu', 'remove_menus' );

Tuesday, November 29, 2016

Add pagination in wordpress admin in customized plugin

Add pagination in wordpress admin in customized plugin

Create folder name admin_menu path wp-content\plugins\admin_menu

Create php file name admin_menu path wp-content\plugins\admin_menu\admin_menu.php

admin_menu.php source code

<?php
/**
* Plugin Name: Admin Menu
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom admin menu.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
function theme_options_panel(){
  add_menu_page('Theme page title', 'Theme menu', 'manage_options', 'theme-options', 'wps_theme_func');
  add_submenu_page('theme-options', 'Settings page title', 'Settings menu label', 'manage_options', 'theme-op-settings', 'wps_theme_func_settings');
  add_submenu_page('theme-options', 'FAQ page title', 'FAQ menu label', 'manage_options', 'theme-op-faq', 'wps_theme_func_faq');
  add_submenu_page('theme-options', 'My List Table', 'My List Table', 'manage_options', 'my-list-table', 'wps_theme_list_table');

}
add_action('admin_menu', 'theme_options_panel');

//function
function wps_theme_func(){
    echo '<div class="wrap">
 <div id="icon-users" class="icon32"></div>
 <h2>Theme Options</h2>
 </div>';
}
function wps_theme_func_settings(){
    echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
    <h2>Settings</h2></div>';
}
function wps_theme_func_faq(){
    echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div>
    <h2>FAQ</h2></div>';
}
function wps_theme_list_table(){
    echo '<div class="wrap">
 <div id="icon-users" class="icon32"></div>
 <h2>My List Table Test - Pagination</h2>
 </div>';
 global $wpdb;
 echo '<form method="get" action="" id="posts-filter">
  <table class="wp-list-table widefat fixed pages">
  <tbody id="the-list">
   <thead>
    <tr>
  <th class="manage-column column-cb check-column" id="cb" scope="col"></th>
  <th class="manage-column column-name" scope="col">User ID</th>
  <th class="manage-column column-name" scope="col">Invoice #</th>
  <th class="manage-column column-name" scope="col">Date Order</th>
  <th class="manage-column column-name" scope="col">Paid By</th>
  <th class="manage-column column-name" scope="col">Action</th>
    </tr>
   </thead>
   <tfoot>
    <tr>
  <th class="manage-column column-cb check-column" scope="col"></th>
  <th class="manage-column column-name" scope="col">User ID</th>
  <th class="manage-column column-name" scope="col">Invoice #</th>
  <th class="manage-column column-name" scope="col">Date Order</th>
  <th class="manage-column column-name" scope="col">Paid By</th>
  <th class="manage-column column-name" scope="col">Action</th>
    </tr>
   </tfoot>';
    $pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
    $limit = 3; // number of rows in page
    $offset = ( $pagenum - 1 ) * $limit;
    $total = $wpdb->get_var( "SELECT COUNT('id') FROM wp_sdn_userorder" );
    $num_of_pages = ceil( $total / $limit );
    $sql_usersorder = $wpdb->get_results( "SELECT * FROM wp_sdn_userorder ORDER BY dateorder DESC LIMIT $offset, $limit");
    $totalrec =  $wpdb->num_rows;
    $isodd=array('','alternate');
    $n=0;
    foreach ($sql_usersorder as $rows_usersorder) 
    {
  $n++;
  $id = $rows_usersorder->id;   
  $user_id = $rows_usersorder->user_id;
  $course_invoice = $rows_usersorder->course_invoice;
  $dateorder = $rows_usersorder->dateorder;
  $paidby = $rows_usersorder->paidby;
  echo '<tr class="type-page '.$isodd[$n%2].'">
  <th class="check-column" scope="row"><center>'.$n.'</center></th> 
  <td class="column-title"><strong><a title="Edit" href="#" class="row-title">'.$user_id.''.rand().'</a></strong>
  <div class="row-actions">
  <span class="edit"><a title="Edit this item" href="#">Edit</a> | </span>
  <span class="trash"><a href="javascript:delusers('.$id.','.$user_id.')" title="Move this item to the Trash" class="submitdelete">Trash</a> | </span>
  </div>
    </td>
    <td>'.$course_invoice.'</td>
    <td>'.$dateorder.'</td>  
    <td>'.$paidby.'</td>
    <td><a href="#">View</a> | <a href="#">Delete</a></td>
  </tr>';
    }
   echo '</tbody>
  </table>
  <div class="tablenav bottom">
   <div class="alignleft actions bulkactions">';
    $page_links = paginate_links( array(
  'base' => add_query_arg( 'pagenum', '%#%' ),
  'format' => '',
  'prev_text' => __( '«', 'text-domain' ),
  'next_text' => __( '»', 'text-domain' ),
  'total' => $num_of_pages,
  'current' => $pagenum
    ) );
    if ( $page_links ) {
  echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
    }
   echo '</div>
   <br class="clear">
  </div>
 </form>';
}

Friday, June 24, 2016

Wordpress - You do not have sufficient permissions to access this page.

Wordpress - You do not have sufficient permissions to access this page.

You should check your wp-config.php file and if you find this line
define('DISALLOW_FILE_MODS',true);
change its value to false:
define('DISALLOW_FILE_MODS',false);
 

Thursday, July 25, 2013

Using Sessions in WordPress Plugins

Using Sessions in WordPress Plugins 

In your theme/plugin

Add the next piece of code to your functions.php or plugin file to enable sessions:

/**
 * init_sessions()
 *
 * @uses session_id()
 * @uses session_start()
 */
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

Thursday, June 28, 2012

Create a URL from a string of text with PHP like wordpress

Create a URL from a string of text with PHP like wordpress
<?php
function create_slug($string){
   $string = preg_replace( '/[«»""!?,.!@£$%^&*{};:()]+/', '', $string );
   $string = strtolower($string);
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}
$slug = create_slug('This is my page title');
echo $slug;
// this should print out: this-is-my-page-title
?>

Friday, March 25, 2011

How to: Add a Share on facebook link to your WordPress blog

How to: Add a Share on facebook link to your WordPress blog

Paste the following code on your single.php file, within the loop:








<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" target="blank">Share on Facebook</a>

Sunday, March 6, 2011

Displaying Number of Comments in your WordPress Blog

Displaying Number of Comments in your WordPress Blog

<?php
$numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $numcomms) $numcomms = number_format($numcomms);
echo "There's ".$numcomms." total comments on my blog";
?>

Display Most Popular Posts in WordPress

Display Most Popular Posts in WordPress








<h2>Popular Posts</h2>
<ul>

<?php $result = $wpdb->get_results("SELECT
comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count
DESC LIMIT 0 , 5");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>

<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>

Just change the 5 in line 3 to change the number of displayed popular posts

Monday, February 28, 2011

get the ID of the last insert post in WordPress

get the ID of the last insert post in WordPress

<div id="div1">
<?php
//insert new post
// Create post object
$my_post = array();
$my_post['post_title'] = 'Hello world';
$my_post['post_content'] = 'This is a sample post';
$my_post['post_status'] = 'published';
$my_post['post_author'] = 7; //the id of the author
$my_post['post_category'] = array(10,12); //the id's of the categories

// Insert the post into the database
$post_id = wp_insert_post( $my_post ); //store new post id into $post_id

//now add tags to new post
$tags = array('html', 'css', 'javascript');
wp_set_object_terms( $post_id, $tags, 'post_tag', true );

?>
</div>

Related Post