<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>WordPress Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/wordpress/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Fri, 09 Aug 2024 21:32:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Let’s build a WordPress theme with React: Part 3 (The Loop)</title>
		<link>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/</link>
					<comments>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 03 Oct 2019 21:24:06 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6985</guid>

					<description><![CDATA[<p>Okay its been a while since I last posted. Let&#8217;s continue with Barebones React WP theme. The last time we left off, we introduced the concept of &#8220;The Loop&#8220;. But we really didn&#8217;t get into what its all about. Let&#8217;s describe what this piece is doing. In WordPress themes &#8211; there is the &#8220;The Loop&#8220;, [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Let’s build a WordPress theme with React: Part 3 (The Loop)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Okay its been a while since I last posted. Let&#8217;s continue with Barebones React WP theme. The last time we left off, we introduced the concept of &#8220;<strong>The Loop</strong>&#8220;. But we really didn&#8217;t get into what its all about. Let&#8217;s describe what this piece is doing. </p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="700" height="400" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp.jpg" alt="react wordpress" class="wp-image-6940" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp.jpg 700w, https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp-300x171.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></figure>



<p>In WordPress themes &#8211; there is the &#8220;<a href="https://codex.wordpress.org/the_loop">The Loop</a>&#8220;, where it&#8217;s a &#8220;catch all&#8221; for all of the post content at a given query. This may be a page, a post or a series of posts. It all goes to &#8220;<strong>The Loop</strong>&#8220;, where inside that loop &#8211; are methods that make retrieving post data easy. Inside the loop, we can do something like &#8220;<em>get_the_ID()</em>&#8221; or &#8220;<em>the_title()</em>&#8221; &#8211; which will output the post id or its title. </p>



<p>We&#8217;re trying to achieve the same thing in Barebones. We have &#8220;TheLoop&#8221; component &#8211; which we&#8217;ll be adding in our &#8220;partials&#8221; directory. This component will be used everywhere &#8211; in single posts, pages or archive pages such as search etc. </p>



<p>Previously, we were just outputting the slug in TheLoop. The modified version is shown below. </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import WithConsumer from '../context/WithConsumer';
import ThePost from './ThePost';
const TheLoop = ({ context }) =&gt; {
    const posts = () =&gt; context.posts;
    const pos = posts();
    let results = '';
    if(context.appError){
      results = &lt;div className="app-error"&gt;{context.appError}&lt;/div&gt;;
    }else{
      if(pos.length === 0){
        results = &lt;div className="no-results"&gt;no results&lt;/div&gt;;
      }else{
        results = pos.map(function(item,i){
             return &lt;ThePost key={i} index={i}&gt;&lt;/ThePost&gt;
           })
      }
    }
    return (results);
};
export default WithConsumer(TheLoop);</code></pre>



<p>There&#8217;s really not a lot going on. We are simply isolating the &#8220;loop&#8221; logic in this component. So we don&#8217;t have to do the same elsewhere. But the key points to see is we&#8217;re getting the results from our Context. And depending on the count of the result, if there&#8217;s more than 0, we &#8211; return the &#8220;<strong>ThePost</strong>&#8221; component (more on this later).</p>



<p>If there&#8217;s no results &#8211; we simply return a div with the text &#8220;no results&#8221;. </p>



<p>If  there&#8217;s an error &#8211; return the error message. </p>



<h3 class="wp-block-heading">ThePost</h3>



<p>ThePost component has all of the methods necessary to output the post data. This resembles WP&#8217;s &#8220;<strong>the_post()</strong>&#8221; in PHP. In here, we have access to the context.posts, filtered by the index. The index is a prop that we pass coming from TheLoop. So now, each <strong>item</strong> is a post:</p>



<pre title="ThePost" class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">const ThePost = ({index,context}) =&gt; {
    const posts = () =&gt; context.posts;
    const item = posts()[index];
    let linkPrefix = item.type === 'page' ? '/page/' : '/post/';
    let theContent = '';
    switch(context.route){
        case '/': //if homepage,
        case '/search/:term': //or if search
        case '/category/:catid': //or if search
            theContent = item.excerpt.rendered; //show excerpt only
        break;
        default: //for single, pages - show entire content
            theContent = item.content.rendered;
        break;
    }
    return (
        &lt;div id={'post-id-'+item.id} className={'post-item'}&gt;
            &lt;h1&gt;&lt;Link to={linkPrefix+item.slug}&gt;{item.title.rendered}&lt;/Link&gt;&lt;/h1&gt;
            &lt;PostMeta index={index}&gt;&lt;/PostMeta&gt;
            &lt;div className="post-content" dangerouslySetInnerHTML={{__html:theContent}}&gt;&lt;/div&gt;
        &lt;/div&gt;);
};</code></pre>



<p>We have to determine if its a &#8220;post&#8221; or a &#8220;page&#8221; (line 6). This will match with the post/page route in our <em>index.js</em>.  </p>



<p>Then we have a switch statement, that checks the route. If its an archive page (like search, category) &#8211; let&#8217;s output only the content excerpt. Otherwise &#8211; if its a single, let&#8217;s output the entire thing. </p>



<p>The PostMeta component is also a new component that we haven&#8217;t built yet. Let&#8217;s add that in a little bit. For now, let&#8217;s grab the data.</p>



<h3 class="wp-block-heading"><strong>Context</strong>.js</h3>



<p>Now there are a few things we need to do to our Context component for the loop to work. Remember in our loop, we&#8217;ve setup up the links using &#8220;Link to&#8221;. We need to map these links to right REST url endpoint &#8211; so we can get the right data and put it in the right data store. </p>



<p>Remember, all of the data is inside this one file. May it be posts, comments &#8211; even methods that manipulate this data is in this component. So this file is extremely important. </p>



<p>Let&#8217;s start by adding the containers for our state. In the constructor, add the following:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">constructor(props) {
    super(props);
    let restType = this.getRestType(props.router.match.path);
    let route = props.router.match.path;
    let slug = props.router.match.params.slug ? props.router.match.params.slug : '';
    this.state = {
      slug : slug,
      restType : restType,
      route : route,
      posts : []
    };
  }</code></pre>



<p>Our state now has the necessary containers for the data we need. Primarily the &#8220;posts&#8221; array is what we aim to fill. Let&#8217;s add some actions in our lifecycle hook: componentDidMount:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">componentDidMount(){
    this.getPosts(this.buildUrl());
}</code></pre>



<p>Let&#8217;s build a couple of functions &#8211; one to build the REST url endpoint, and the other to fetch the posts: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">buildUrl(){
    let url = '/wp-json/wp/v2/';
    switch(this.state.restType){
      case 'page':
        url += 'pages/?slug=' + this.state.slug
      break;
      case 'post':
      default:
        url += 'posts/?slug=' + this.state.slug ;
        break;
    }
    return url;
  }
 getPosts (url){
    let self = this;
    Axios.get(url).then((response)=&gt;{
      self.setState({
        posts : response.data
    }).catch(function(error){
      console.log(error);
      self.appError = 'An unexpected error occurred';
    });
  }
</code></pre>



<p>That should set our post and page endpoints, bringing back data from the API.  Make sure that TheLoop is in your Archive and Single components. </p>



<p>And if all is good, we should have something like below: </p>



<figure class="wp-block-image border"><img decoding="async" width="700" height="527" src="https://michaelsoriano.com/wp-content/uploads/2019/06/post-page.gif" alt="" class="wp-image-6986"/></figure>



<p>Remember that we have to change our permalinks in WordPress to match our route. </p>



<h3 class="wp-block-heading">Add Paging</h3>



<p>Paging is necessary especially for archive pages. You only want to see the latest X number of posts, then show the next X &#8211; and so on. </p>



<p>In <strong>Archive.js</strong> &#8211; simply add the pager component (that we still have to build), right underneath the loop:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx"> &lt;TheLoop&gt;&lt;/TheLoop&gt;
 &lt;Pager&gt;&lt;/Pager&gt;</code></pre>



<p>Now let&#8217;s create a file in our partials folder &#8211; call it <strong>Pager.js</strong>. </p>



<pre title="Pager.js" class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React, { useEffect } from 'react';
import WithConsumer from '../context/WithConsumer';
const Pager = function ({context}){
    let prevBtn =  React.createRef();
    let nextBtn =  React.createRef();
    let curPage = () =&gt; context.currentPage;
    let totalPages = () =&gt; context.totalPages;
    useEffect(() =&gt; {
        prevBtn.current.disabled = true;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[]);
    function nextClicked(){
        context.nextClicked();
        if(parseInt(totalPages()) === parseInt(curPage() + 1) ){
            nextBtn.current.disabled = true;
        }
        prevBtn.current.disabled = false;
    }
    function previousClicked(){
        context.previousClicked();
        if(parseInt(curPage()-1) === 1 ){
            prevBtn.current.disabled = true;
        }
        nextBtn.current.disabled = false;
    }
    function pagerClass(){
        let cls = 'Pager';
        if(parseInt(totalPages()) &lt;=1 ||
            context.appError){
            cls = 'Pager hidden';
        }
        return cls;
    }
    return (
        &lt;div className={pagerClass()}&gt;
        &lt;button ref={prevBtn} onClick={previousClicked}&gt;Previous&lt;/button&gt;
        &lt;button ref={nextBtn} onClick={nextClicked}&gt;Next&lt;/button&gt;
        &lt;div className="PagerText"&gt;Page
            &lt;span dangerouslySetInnerHTML={{__html: curPage()}}&gt;&lt;/span&gt; of
            &lt;span dangerouslySetInnerHTML={{__html: totalPages()}}&gt;&lt;/span&gt;&lt;/div&gt;
        &lt;/div&gt;
    )
}
export default WithConsumer(Pager);</code></pre>



<p>Now the pager logic is a little more involved. Above simply outputs our &#8220;Next&#8221; and &#8220;Previous&#8221; buttons &#8211; depending on the number of pages. Fortunately, WordPress&#8217;s API makes this easy for us. We have 2 important header properties from each response called &#8221; X-WP-Total&#8221; and &#8221; X-WP-TotalPages&#8221;. From this we can determine the logic needed for our paging.</p>



<p>Going back to context, we need to modify our state, add some methods that modify that state, as well as modify our rest calls.</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">//ADD THIS TO this.state IN THE CONSTRUCTOR
currentPage : 1,
totalPages : 0,
nextClicked : this.nextClicked.bind(this),
previousClicked : this.previousClicked.bind(this), </code></pre>



<p>Above shows our new state. Note that currentPage always starts at 1. Totalpages &#8211; we update on every call, then we bind 2 methods to &#8220;this&#8221;. </p>



<p>Next, let&#8217;s add modify our <strong>buildUrl()</strong> method to have the page parameters from our state. </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx"> case 'post':
      default:
        url += this.state.slug ? 'posts/?slug=' + this.state.slug : 'posts/?page=' + this.state.currentPage;
        break;    </code></pre>



<p>Above simply appends the current page to the url endpoint. In our <strong>getPosts()</strong> method, we update our totalPages in state with each response: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">Axios.get(url).then((response)=&gt;{
      self.setState({
        posts : response.data,
        totalPages : response.headers['x-wp-totalpages']
      }</code></pre>



<p>Now all we need to do is create two functions &#8211; which correspond to which button was clicked: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">  nextClicked (){
    let newPage = this.state.currentPage + 1;
    this.setState({
      currentPage : newPage
    },function(){
      this.getPosts(this.buildUrl());
    })
  }
  previousClicked (){
    let newPage = this.state.currentPage - 1;
    this.setState({
      currentPage : newPage
    },function(){
      this.getPosts(this.buildUrl());
    })
  }</code></pre>



<p>Both of these methods are called from our Pager component &#8211; which we access by doing <em>context.XXXClicked()</em>. Pretty neat right? </p>



<p>We also let the front end decide whether to show or hide the respective buttons. So if all goes well, we have something like below: </p>



<figure class="wp-block-image border"><img decoding="async" width="700" height="572" src="https://michaelsoriano.com/wp-content/uploads/2019/06/paging.gif" alt="" class="wp-image-6988"/></figure>



<p>Okay that should be it for this round. A lot going on above. I suggest you download the <a href="https://github.com/michaelsoriano/barebones">code</a> and run it yourself &#8211; along with following the steps. Note there are a lot of omitted code above. Only the important steps are outlined &#8211; the rest is up to you.</p>
<p>The post <a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Let’s build a WordPress theme with React: Part 3 (The Loop)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Let’s build a WordPress theme with React: Part 2 (Routes + Context)</title>
		<link>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/</link>
					<comments>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 15 Jul 2019 04:10:50 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=7030</guid>

					<description><![CDATA[<p>Now that we have our react app setup, let&#8217;s form how our application will be structured. We&#8217;re going to need 3 main folders: 1) templates, 2) partials and 3) context. These are all going to be inside react-src/src folder. The templates folder is where we&#8217;re going to store the main files template files &#8211; namely [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Let’s build a WordPress theme with React: Part 2 (Routes + Context)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><!--StartFragment--></p>

<p>Now that we have our react app setup, let&#8217;s form how our application will be structured. We&#8217;re going to need 3 main folders: 1) <em>templates, </em>2) <em>partials </em>and 3) <em>context</em>. These are all going to be inside <strong>react-src/src</strong> folder.</p>


<p>The <strong>templates</strong> folder is where we&#8217;re going to store the main files template files &#8211; namely <em>Single.js</em> and <em>Archive.js.</em> Single shows a single post, while Archive shows a running list of post in reverse chronological order. </p>


<p>The <strong>partials</strong> contain bits and pieces of reusable parts. These are files that make up the header, navigaition, pagination and the loop.</p>


<p>The <strong>context</strong> is where the data sits. We&#8217;re going to have two files in here &#8211; <em>Context.js</em> and <em>WithConsumer.js</em>. These files are what we need to store state and props. More on this later. </p>


<p>Also, don&#8217;t forget that we have our <strong>public</strong> folder (which is outside the src directory). This contains all the regular PHP files such as functions.php etc.</p>


<h3 class="wp-block-heading">Routes</h3>


<p>Let&#8217;s begin by adding a simple route. Make sure we&#8217;re in development mode by running:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">npm run wpstart</code></pre>


<p>Let&#8217;s create a new component called &#8220;Single&#8221;. Inside it, let&#8217;s start simple and put in the code below: </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">import React from 'react';
const Single = (props) => {
    return (
        &lt;div className="Post">
            this is the page component
        &lt;/div>
    )
}
export default Single;</code></pre>


<p>Pretty basic right? Now let&#8217;s install react router by running the command below: </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">npm install react-router-dom</code></pre>


<p>Open up <strong>index.js</strong> and include react router in it</p>


<pre class="wp-block-code"><code lang="bash" class="language-bash">import { BrowserRouter, Switch, Route } from 'react-router-dom';</code></pre>


<p>Inside the render function, let&#8217;s modify it to look like this: </p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">ReactDOM.render(
&lt;BrowserRouter>
    &lt;Switch>
     &lt;Route path='/page' component={Single}/>
    &lt;/Switch>
  &lt;/BrowserRouter>, document.getElementById('root'));</code></pre>


<p>Now navigate to your site, but append the path &#8220;/page&#8221;. You should see your page component rendered. </p>


<figure class="wp-block-image"><img decoding="async" width="599" height="487" src="https://michaelsoriano.com/wp-content/uploads/2019/06/page-component.png" alt="" class="wp-image-6970" srcset="https://michaelsoriano.com/wp-content/uploads/2019/06/page-component.png 599w, https://michaelsoriano.com/wp-content/uploads/2019/06/page-component-300x244.png 300w" sizes="(max-width: 599px) 100vw, 599px" /></figure>


<p>Now let&#8217;s go back to <strong>index.js</strong> and modify the Route to look like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;Route path="/page/:slug" component={Single} />    </code></pre>


<p>Notice we&#8217;re adding a <strong>:slug</strong> to the path. We&#8217;re going to be updating our component with this parameter. The slug will be the actual &#8220;slug&#8221; of the WordPress post. If you modify our page component with:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;h1>this is the slug: {props.match.params.slug}&lt;/h1></code></pre>


<p>You should see something like below:</p>


<figure class="wp-block-image"><img decoding="async" width="599" height="430" src="https://michaelsoriano.com/wp-content/uploads/2019/06/slug.png" alt="" class="wp-image-6971" srcset="https://michaelsoriano.com/wp-content/uploads/2019/06/slug.png 599w, https://michaelsoriano.com/wp-content/uploads/2019/06/slug-300x215.png 300w" sizes="(max-width: 599px) 100vw, 599px" /></figure>


<p>So by now, you should see how we&#8217;re going to continue with our theme. We&#8217;re going to be adding the following routes:</p>


<ul class="wp-block-list"><li>Home &#8211; mapped to &#8220;Archive&#8221;</li><li>Page + slug &#8211; mapped to &#8220;Single&#8221;</li><li>Post + slug &#8211; mapped to &#8220;Single&#8221;</li><li>Search + term &#8211; mapped to &#8220;Archive&#8221;</li><li>404 &#8211; mapped to &#8220;404&#8221;</li></ul>


<p>Go ahead and copy the Single component, duplicate it &#8211; and call it &#8220;Archive&#8221;.  Then let&#8217;s match it to the routes above. </p>


<p>Our <strong>index.js</strong> now looks like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'
import './index.css';
import Archive from './templates/Archive';
import Single from './templates/Single';
import Notfound from './templates/Notfound';
const routes = (
    &lt;Router>
      &lt;Switch>
           &lt;Route exact path="/" component={Archive} />
           &lt;Route path="/page/:slug" component={Single} />
           &lt;Route path="/post/:slug" component={Single} />
           &lt;Route path="/search/:term" component={Archive} />
           &lt;Route component={Notfound} />
      &lt;/Switch>
    &lt;/Router>
  )
ReactDOM.render(routes, document.getElementById('root'));</code></pre>


<p><strong>Partials</strong></p>


<p>Let&#8217;s quickly talk about our partials. Partials are components that we will be reusing in each route component. Things that come to mind are header, footer, sidebar &#8211; and whichever reusable piece of code we will come across along the way.</p>


<p>Let&#8217;s go ahead and create 2 partials. <strong>Head.js</strong> and <strong>Foot.js</strong>. These will be the header and footer of our pages. The code will be a simple functional component like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">/******Head.js*************/
import React from 'react'
function Head(){
    return (&lt;div className="header">header&lt;/div>)
}
export default Head;
/******Foot.js*************/
import React from 'react'
function Foot(){
    return (&lt;div className="footer">footer&lt;/div>)
}
export default Foot;</code></pre>


<p>Now in our template components, simply import, and add the components in. Here is the how our <strong>Single.js</strong> will look like with the partials. Note &#8211; make sure you add them inside the main div:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react'
import Head from '../partials/Head';
import Foot from '../partials/Foot';
const Single = (props) => {
    return (
        &lt;div className="Post">
            &lt;Head>&lt;/Head>
            &lt;h1>Home&lt;/h1>
            &lt;Foot>&lt;/Foot>
        &lt;/div>
    )
}
export default Single</code></pre>


<p>In the browser, you will see our partials and home page starting to take shape. Inspect the code and it should look like below:</p>


<figure class="wp-block-image"><img decoding="async" width="678" height="424" src="https://michaelsoriano.com/wp-content/uploads/2019/06/partials.gif" alt="" class="wp-image-6978"/></figure>


<p>Do the same thing to the rest of our main components so they all share the same header and footer. </p>


<h3 class="wp-block-heading">Context (Data)</h3>


<p>As mentioned above, this is where our data will sit. React has <a href="https://reactjs.org/docs/context.html">Context API</a> which allows you to have a centralized data store &#8211; so that you don&#8217;t have to pass data through each child component. This <a href="https://medium.com/datadriveninvestor/getting-started-w-reacts-context-api-f60aa9be758f">article</a> is probably the best explanation on Context API. As a matter of fact, the two files that we&#8217;re going to build, is code that came from the article. </p>


<p>Let&#8217;s start with <strong>Context.js</strong>. This file is considered to be the &#8220;<em>Provider</em>&#8220;. Add the code below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from "react";
const storeContext = React.createContext();
export const Consumer = storeContext.Consumer;
export class Provider extends React.Component {
  constructor(props) {
    super(props);
     this.state = {
      posts : []
    };
  }
 componentDidMount(){
    this.setState({
       posts : ['title','title2']
    })
 }
 componentDidUpdate(prevProps){
    //more code here later...
 }
 render() {
    return (
      &lt;storeContext.Provider value={this.state}>
        {this.props.children}
      &lt;/storeContext.Provider>
    );
  }
} </code></pre>


<p>Don&#8217;t worry so much about the test posts data. We&#8217;re just using that for &#8211; well, testing. Then let&#8217;s create <strong>WithConsumer.js</strong></p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from "react";
import { Consumer } from "./Context";
function WithConsumer(WrappedComponent) {
  return function(props) {
    return (
      &lt;Consumer>
        {ctx => &lt;WrappedComponent {...props} context={ctx} />}
      &lt;/Consumer>
    );
  };
}
export default WithConsumer;</code></pre>


<p>Now this one is pretty confusing. It&#8217;s basically a wrapper &#8211; for our components that require the &#8220;Consumer&#8221; component. Basically, all our components that want to &#8220;consume&#8221; data from our &#8220;Provider&#8221; will be using this file. </p>


<p>Now let&#8217;s create a partial called &#8220;<strong>TheLoop</strong>&#8220;. Add the code below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import WithConsumer from '../context/WithConsumer';
const TheLoop = ({ context }) => {
    const posts = () => context.posts;
    const pos = posts();
    return (
       pos.map(function(item,i){
         return &lt;div key={i}>{item}&lt;/div>
       })
    );
};
export default WithConsumer(TheLoop);</code></pre>


<p>Notice that in our export &#8211; we&#8217;re passing our component <strong>TheLoop</strong> as a parameter to <strong>WithConsumer</strong>.  </p>


<p>We&#8217;re going to talk more in detail about <strong>TheLoop</strong> component in our next session. For now, we just want to get it up and running &#8211; to demonstrate Context and Consumer. </p>


<p>Let&#8217;s open <strong>Single.js</strong> from our templates folder and modify it to look like this:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">import React from 'react';
import Head from '../partials/Head';
import TheLoop from '../partials/TheLoop';
import Foot from '../partials/Foot';
import {Provider} from '../context/Context'
const Single = (props) => {
  return (
    &lt;Provider>
    &lt;div className="Post">
      &lt;Head>&lt;/Head>
      &lt;TheLoop>&lt;/TheLoop>
      &lt;Foot>&lt;/Foot>
    &lt;/div>
    &lt;/Provider>
  )
}
export default Single</code></pre>


<p>You see how we&#8217;re wrapping everything in &#8220;<strong>&lt;Provider&gt;</strong>&#8220;, this is so we have access to our <strong>Context.js</strong> data. Also, we&#8217;ve included &#8220;<strong>TheLoop</strong>&#8221; as a component in between Head and Foot. </p>


<p>You should see &#8220;title&#8221; and &#8220;title2&#8221; in the browser by now. </p>


<p>Lastly, we need a way to get our &#8220;slug&#8221; parameter into our context. We can use props for that. Still in <strong>Single.js</strong>, pass the slug via props like so:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;Provider router={props}></code></pre>


<p>In <strong>Context.js</strong>, we should have access to the slug &#8211; through &#8220;<strong>props.router.match.params.slug</strong>&#8220;. As a matter of fact, we have access to the entire router object here, in a prop called &#8220;router&#8221;. </p>


<p>Let&#8217;s stop here for now. We are going to discuss more about <strong>TheLoop</strong> and Axios in our next session.</p>

<p><!--EndFragment--></p><p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Let’s build a WordPress theme with React: Part 2 (Routes + Context)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/feed/</wfw:commentRss>
			<slash:comments>58</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</title>
		<link>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/</link>
					<comments>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 21 May 2019 16:38:24 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6909</guid>

					<description><![CDATA[<p>It&#8217;s been a while since I worked with WordPress, especially building themes. This time around, I wanted to bring in a bit more modern development experience into the process. I wanted to build a Single Page Application (SPA), with WordPress&#8217; Rest API &#8211; but as a WordPress theme. The problem is, this can be a [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>It&#8217;s been a while since I worked with <a href="http://automattic.pxf.io/nL7v4x" rel="nofollow">WordPress</a>, especially building themes. This time around, I wanted to bring in a bit more modern development experience into the process. I wanted to build a Single Page Application (SPA), with WordPress&#8217; Rest API &#8211; but as a WordPress theme. The problem is, this can be a pain to setup. Especially with the build step and all.</p>



<p>I specifically wanted to use <a href="https://reactjs.org"><strong>React</strong></a><strong> </strong>for the front end. React is Facebook&#8217;s product, and per their website: <em>React is a library for building user interfaces</em>. It has a very broad user base and lots of modules available, which makes it ideal for our theme. In conjunction, we&#8217;re using <strong><a href="https://www.npmjs.com/package/create-react-wptheme">create-react-wptheme</a></strong> &#8211; which will make our theme up and running with React in no time. And of course, WP Rest API for the backend.</p>



<p><img decoding="async" width="1348" height="891" src="https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq.png" alt="react" class="wp-image-7237" srcset="https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq.png 1348w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-300x198.png 300w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-1024x677.png 1024w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-768x508.png 768w" sizes="(max-width: 1348px) 100vw, 1348px" /></p>



<p>Note that this tutorial is geared towards PHP or WordPress developers &#8211; who are looking to get started working with Single Page Applications with React. </p>



<p>This will be the first of a series of posts: </p>



<ul class="wp-block-list">
<li><a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Part 1 &#8211; Setup</a> </li>



<li><a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Part 2 &#8211; Routes + Context</a></li>



<li><a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Part 3 &#8211; The Loop</a></li>
</ul>



<p>The theme we&#8217;re going to build throughout this series is more of a <em>starter</em> theme. We&#8217;re calling it &#8220;barebones&#8221; and it contains just the right amount of functionality for a basic WordPress theme.  </p>



<p>We will need the following to get started: </p>



<ul class="wp-block-list">
<li>nodejs + npm</li>



<li>git bash (or terminal)</li>



<li>local WordPress installation</li>
</ul>



<h3 class="wp-block-heading">create-react-wptheme </h3>



<p>Let&#8217;s talk briefly about create-react-wptheme.  The goal is to get us <em>bootstrapped</em> with a new React based WordPress theme with a few commands. If any of you are familiar with create-react-app, its basically the same functionality &#8211; but for WordPress. One primary difference is that it uses WordPress (not webpack), as the development server. This makes development consolidated in one &#8211; front end and back end. </p>



<p>In addition, since it&#8217;s a WordPress theme, you have access to all the core functions, filters, actions, hooks etc. Also, you can use WordPress&#8217; nonce for authenticated requests. Lastly, if you must use plain PHP &#8211; say only for a specific page, you can still use WordPress&#8217; page templates &#8211; which is very handy.</p>



<p>So with that in mind, let&#8217;s get started. </p>



<p>First, assuming you have a local WordPress installation, go ahead and start a terminal (git bash) in the themes directory. </p>



<figure class="wp-block-image"><img decoding="async" width="600" height="560" src="https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3.png" alt="" class="wp-image-6955" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3.png 600w, https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3-300x280.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></figure>



<p>In Windows, git bash is a pretty good tool, simply right click and &#8220;Git Bash Here&#8221;. This will launch the terminal, where we can start our installation. Type in the command below:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">npx create-react-wptheme barebones</code></pre>



<p>Note that &#8220;barebones&#8221; is the name of our theme. You can simply replace this with a theme name of your preference.</p>



<figure class="wp-block-image"><img decoding="async" width="500" height="355" src="https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1.png" alt="npm install" class="wp-image-6921" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1.png 500w, https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1-300x213.png 300w" sizes="(max-width: 500px) 100vw, 500px" /></figure>



<p>Once that&#8217;s done, you will see a message like above. The installation created a root folder, with a &#8220;react-src&#8221; directory inside it. Consider the react-src directory as the most important directory because it holds all of your un-compiled code. From this directory &#8211; we can build the rest. You&#8217;ll see what I mean later.</p>



<p>Note that at this step, our theme is not ready yet.  </p>



<p>See, if you look inside <em>wp-admin</em> &gt; <em>themes</em>, you will see &#8220;barebones&#8221; under the &#8220;Broken Themes&#8221; section.</p>



<figure class="wp-block-image"><img decoding="async" width="549" height="170" src="https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css.png" alt="broken theme" class="wp-image-6923" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css.png 549w, https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css-300x93.png 300w" sizes="(max-width: 549px) 100vw, 549px" /></figure>



<p>This is because we don&#8217;t have the necessary files (mainly the styles.css) for it to be a valid theme. Note that we also need index.php, so the we can hold the JavaScript and CSS files together. </p>



<h3 class="wp-block-heading">wpstart</h3>



<p>Let&#8217;s go back to our terminal and type the following:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">cd barebones/react-src
npm run wpstart</code></pre>



<p>We&#8217;re going into our theme directory and inside &#8220;react-src&#8221; by using the &#8220;cd&#8221; command, then we run <strong>wpstart</strong>. This will fix the &#8220;Broken Themes&#8221; issue, and if we go back to the browser and go in <em>wp-admin</em> &gt; <em>themes</em> themes, you should be able to see our theme.  </p>



<figure class="wp-block-image"><img decoding="async" width="610" height="395" src="https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin.png" alt="wp admin" class="wp-image-6925" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin.png 610w, https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin-300x194.png 300w" sizes="(max-width: 610px) 100vw, 610px" /></figure>



<p>Now let&#8217;s activate the theme by clicking &#8220;<strong>Activate</strong>&#8220;. This will tell WordPress to use this theme we just built. Now let&#8217;s go and view our site in the browser. You should see a message </p>



<p>&#8220;<em>Please restart the Nodejs watcher now&#8230;</em> &#8220;</p>



<p>What this means is that we have to run  <strong>wpstart</strong> a second time, for the script finish setting things up. Let&#8217;s go back to git bash and do a &#8220;CTRL +  C&#8221;. Then type in:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">npm run wpstart</code></pre>



<p>Now, once this is done, a new browser tab should have opened automatically and looks like below: </p>



<figure class="wp-block-image"><img decoding="async" width="631" height="508" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react-app.png" alt="react app" class="wp-image-6929" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react-app.png 631w, https://michaelsoriano.com/wp-content/uploads/2019/05/react-app-300x242.png 300w" sizes="(max-width: 631px) 100vw, 631px" /></figure>



<p>It may not look like much, but this tells us a lot. This page indicates that we&#8217;ve just successfully installed our React theme. This  includes the PHP, CSS and JavaScript files, plus all the resources to run our React application. So well done!</p>



<p><strong>Note: wpstart is for &#8220;dev&#8221; mode.</strong></p>



<p>From this point onward, when you&#8217;re in wpstart mode, (when you do <em>npm run wpstart</em>) that means you are in development mode. What this means is that anytime you change something in the react-src directory, the files will get recompiled and placed in the proper places. Any changes will also cause your browser to refresh &#8211; so you see your changes instantly.</p>



<p><strong>Do Not Edit the files in ROOT</strong></p>



<p>The files in the root folder (outside of react-src), is the compiled version of your code that is needed for WordPress and React to run. You shouldn&#8217;t edit anything in here because as soon as you save files in react-src &#8211; the files in the root will be replaced with the new. <u>So anything you change here will get OVERWRITTEN</u>.</p>



<h3 class="wp-block-heading" id="mce_14">File Structure</h3>



<p>Let&#8217;s take a quick look at at the file structure for it&#8217;s important to know what it is and how create-react-wptheme use it. In a regular WordPress theme, all we really need are the PHP (such as header, footer) and CSS. </p>



<p>In our new theme, it looks something like below: </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/root2.png" alt="root folder" class="wp-image-6956" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/root2.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/root2-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>As you can see, there is none of the familiar files you would expect in a WP theme. Remember we&#8217;re building an SPA &#8211; which will all be in JavaScript.</p>



<p>As mentioned previously, inside react-src are the uncompiled and &#8220;editable&#8221; version of your code. Everything else (the root and static folder) are the output of what you have in react-src. Take note of that text file that&#8217;s titled <strong>!DO_NOT_EDIT_THESE_FILES!.txt</strong>. Remember what I said about not editing files in the root?</p>



<p><strong>The &#8220;public&#8221; folder</strong></p>



<p>The author of create-react-wptheme saved a special folder for our non-react files called &#8220;public&#8221;. Whatever you add in this folder, gets copied directly to the root. So, things like functions.php, or page templates &#8211; even CSS or JS can be dumped in here &#8211; and it will get copied into the root at compile time.</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder.png" alt="" class="wp-image-6957" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>Again, this folder can be extremely helpful &#8211; especially for developers who would still like to access core functionality such as hooks, filters, actions etc. </p>



<p>Also, <strong>index.php</strong> &#8211; will only get loaded once, and is the entry way for your React application. The goal is, once loaded, all interactions will be through the REST api. So whatever PHP has produced in <strong>index.php</strong> will stay the same all throughout your application (except PHP page templates).</p>



<p><strong>The &#8220;build&#8221; folder</strong></p>



<p>We haven&#8217;t covered wpbuild yet, but since we talking about the file structure, you will notice a folder called &#8220;<strong>build</strong>&#8220;. This is a special folder that holds the final &#8220;<strong>deployable</strong>&#8221; code. </p>



<p>What that means is, almost like the contents of the &#8220;<strong>root</strong>&#8221; folder, but compressed, minified and optimized for production. Also, it doesn&#8217;t contain any dev files (such as react-src).  </p>



<p>This brings us to the last section: <strong>wpbuild</strong>:</p>



<h3 class="wp-block-heading" id="mce_14">wpbuild</h3>



<p>So let&#8217;s get back to git bash and do CTRL + C.  Type in the following command:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">npm run wpbuild</code></pre>



<p>You will see messaging that looks something like: </p>



<figure class="wp-block-image"><img decoding="async" width="555" height="370" src="https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild.png" alt="" class="wp-image-6942" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild.png 555w, https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild-300x200.png 300w" sizes="(max-width: 555px) 100vw, 555px" /></figure>



<p>This simply shows files that have been created, optimized and placed in the build folder, <strong>as well as the root</strong>. This means that you see your optimized code right away.</p>



<p>To see how that looks, when you refresh your browser, you will see just a bunch of compressed code like this:</p>



<figure class="wp-block-image"><img decoding="async" width="555" height="420" src="https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src.png" alt="" class="wp-image-6943" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src.png 555w, https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src-300x227.png 300w" sizes="(max-width: 555px) 100vw, 555px" /></figure>



<p>Your <a href="http://automattic.pxf.io/nL7v4x" rel="nofollow">WordPress</a> theme&#8217;s source code has been flattened, ready for world consumption. Also, take a look at the contents of the root directory:</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild.png" alt="" class="wp-image-6950" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>You notice the absence of the file <strong>!DO_NOT_EDIT_THESE_FILES!.txt</strong>. That means, that you&#8217;ve just run wpbuild and its now in &#8220;build&#8221; mode. </p>



<p>When you&#8217;re ready to go back to making some changes, don&#8217;t forget to go back into &#8220;dev&#8221; mode, by running &#8220;<em>npm run wpstart</em>&#8221; in the react-src directory.</p>



<p>And there you have it. We have our React application running as a WordPress theme. I&#8217;ve created a <a href="https://github.com/michaelsoriano/barebones">Github repo</a> for Barebones theme. You can go ahead and fork it for your next project, or stay tuned for more tutorials.</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/feed/</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
		<item>
		<title>Show number of posts out of total records  in WordPress</title>
		<link>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/</link>
					<comments>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 15 Mar 2016 02:59:48 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5540</guid>

					<description><![CDATA[<p>From time to time, I just look at my blogs and see what I can add to it to make it more appealing to the user. I&#8217;ve always admired those sites that tell you what number of posts a certain category has, and what number of posts it is currently showing. So I set out [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/">Show number of posts out of total records  in WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>From time to time, I just look at my blogs and see what I can add to it to make it more appealing to the user. I&#8217;ve always admired those sites that tell you what number of posts a certain category has, and what number of posts it is currently showing. So I set out to do just that.<br />
Since I haven&#8217;t written anything WordPress related for a while, I figured this would be good practice. What we&#8217;re writing is something like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5542" src="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1.png" alt="numposts1" width="651" height="389" srcset="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1.png 651w, https://michaelsoriano.com/wp-content/uploads/2016/03/numposts1-300x179.png 300w" sizes="(max-width: 651px) 100vw, 651px" /><br />
You see, we want to show what posts are currently showing &#8211; out of how many total records. It&#8217;s not a hard task &#8211; since all we really need are 2 variables: the current total showing and the total number found.</p>
<h3>The $wp_query Object</h3>
<p>According to the <a href="https://codex.wordpress.org/Class_Reference/WP_Query">codex</a>, the WP_Query class &#8220;deals with the intricacies of a post&#8217;s (or page&#8217;s) request to a WordPress blog&#8221;. This means that WordPress has already done the heavy lifting when it comes to information needed when you query your posts. Information needed when building stuff like paging, queries, templates and meta data.<br />
In our case, we need the meta data &#8211; of the posts returned. So first off, open the index.php file in your theme directory and just outside the loop, add the code below:</p>
<pre>print_r($wp_query);exit;
</pre>
<p>What we&#8217;re doing is seeing what the <strong>$wp_query</strong> is holding. $wp_query is the object that is derived from the WP_Query class that we talked about above. You will see a long array of information that pertains to the current request. So say you&#8217;re in a certain category, this object will contain information about that category and the posts that it contains.<br />
So somewhere in this object lies the information we need. Let&#8217;s grab &#8220;post_count&#8221; and &#8220;found_posts&#8221;.<br />
<img decoding="async" class="alignnone size-full wp-image-5545" src="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2.png" alt="numposts2" width="466" height="592" srcset="https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2.png 466w, https://michaelsoriano.com/wp-content/uploads/2016/03/numposts2-236x300.png 236w" sizes="(max-width: 466px) 100vw, 466px" /><br />
Now that we know the property names, we can go ahead and remove the print_r that we have.</p>
<h3>The Output</h3>
<p>This is as simple as it gets. All we need is to check if &#8220;post_count&#8221; is more than 0 and we can echo out our sentence. We can hard code the &#8220;1&#8221; since we&#8217;re always going to be showing at least 1 record.</p>
<pre><!--?php if($wp_query-&gt;post_count &gt; 0): ?-->
    Showing 1 through <!--?php echo $wp_query-&gt;post_count ?--> out of <!--?php echo $wp_query-&gt;found_posts; ?--> articles..
<!--?php endif; ?-->
</pre>
<p>The code above should work anywhere in your theme. It&#8217;s especially useful in your archive templates &#8211; so users can tell how many articles are in a specific category etc. It&#8217;s a good addition to your paging in the footer as well.<br />
To test it, try searching for something, or click on a category. The &#8220;found_posts&#8221; should depend on the current request, while the &#8220;post_count&#8221; depends on the limit that you have in your WordPress settings.<br />
And that&#8217;s it. Hopefully you can find this snippet useful in your theme somewhere. Please leave your comments below.</p>
<p>The post <a href="https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/">Show number of posts out of total records  in WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/show-number-of-posts-out-of-total-records-in-wordpress/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Add an additional Body Class to WordPress by using the Post Slug</title>
		<link>https://michaelsoriano.com/add-an-additional-body-class-to-wordpress-by-using-the-post-slug/</link>
					<comments>https://michaelsoriano.com/add-an-additional-body-class-to-wordpress-by-using-the-post-slug/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 11 May 2015 02:40:50 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4405</guid>

					<description><![CDATA[<p>One of the real useful things I&#8217;ve come across with WordPress is the body_class() method. This adds several classes to the body element of your HTML. The output looks something like below: Why is this so great? Now you can style your pages very efficiently because you&#8217;re able to select from the template you&#8217;re using, [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/add-an-additional-body-class-to-wordpress-by-using-the-post-slug/">Add an additional Body Class to WordPress by using the Post Slug</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>One of the real useful things I&#8217;ve come across with WordPress is the <a href="https://codex.wordpress.org/Function_Reference/body_class">body_class</a>() method. This adds several classes to the body element of your HTML. The output looks something like below:<br />
<img decoding="async" class="alignnone size-full noborder wp-image-4406" src="https://michaelsoriano.com/wp-content/uploads/2015/05/body-class.jpg" alt="body-class" width="694" height="193" /><br />
Why is this so great? Now you can style your pages very efficiently because you&#8217;re able to select from the template you&#8217;re using, the post type, when user is logged in &#8211; even to the post Id.<br />
An example of what I mean is say &#8211; you want all the H1 tags styled differently only for post ID &#8220;4396&#8221;. Now in you CSS file you can add a rule like below:</p>
<pre>.postid-4396 h1 {
   text-decoration: underline;
   font-size: 45px;
}
</pre>
<p>This will effectively target only that post&#8217;s h1 tags. Pretty useful right?</p>
<h3>Add a Post slug to the Body Class</h3>
<p>Now let&#8217;s take it a step further. If you&#8217;re like me who develop themes all day &#8211; you probably have a local server set up. Now, the problem with that is &#8211; you may not have your WordPress databases the same as the production site. So your post ids may not be the same!<br />
The solution: use the post slug as an additional class. For example, you want to style the &#8220;About us&#8221; page&#8217;s H1 tags differently than the rest of the pages. So instead of relying on the default body_class()&#8217;s post id, simply add the code below to your functions.php file:</p>
<pre>function getPostSlug(){
    global $post;
    $slug = '';
    if(is_object($post)){
       $slug = $post-&gt;post_name;
    }
    return $slug;
}
</pre>
<p>Then, in your header.php file (or where you have your opening body tag is), add the call to the body_class():</p>
<pre>&gt;
</pre>
<p>The output will be something like below:<br />
<img decoding="async" class="alignnone size-full noborder wp-image-4407" src="https://michaelsoriano.com/wp-content/uploads/2015/05/body-class-2.jpg" alt="body-class-2" width="694" height="193" /><br />
Now you can code your CSS like so:</p>
<pre>.about-us h1 {
   text-decoration: underline;
   font-size: 45px;
}
</pre>
<h3>Conclusion</h3>
<p>Pretty neat right? Adding a body class that is based on your post slug is not only very helpful, but also very semantic. The upside of using the slug is its always lowercase and no spaces (unless you change them when you create a post). But then &#8211; you can deal with that accordingly. Tell me your comments below.</p>
<p>The post <a href="https://michaelsoriano.com/add-an-additional-body-class-to-wordpress-by-using-the-post-slug/">Add an additional Body Class to WordPress by using the Post Slug</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/add-an-additional-body-class-to-wordpress-by-using-the-post-slug/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Create a Testimonials section for your WordPress site &#8211; the Right Way!</title>
		<link>https://michaelsoriano.com/create-a-testimonials-section-for-your-wordpress-site-the-right-way/</link>
					<comments>https://michaelsoriano.com/create-a-testimonials-section-for-your-wordpress-site-the-right-way/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 01 Jan 2015 19:12:14 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4247</guid>

					<description><![CDATA[<p>I was recently given the task of updating the testimonials section of our company WordPress site. Imagine my disappointment to see a static page with a running list of paragraphs and author names. I said to myself, we can do way better. Let&#8217;s take a glimpse of what we&#8217;re going to be building: We will [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/create-a-testimonials-section-for-your-wordpress-site-the-right-way/">Create a Testimonials section for your WordPress site &#8211; the Right Way!</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>I was recently given the task of updating the testimonials section of our company WordPress site. Imagine my disappointment to see a static page with a running list of paragraphs and author names. <strong>I said to myself, we can do <i>way</i> better</strong>.<br />
Let&#8217;s take a glimpse of what we&#8217;re going to be building:<br />
<img decoding="async" class="alignnone noborder size-full wp-image-4250" src="https://michaelsoriano.com/wp-content/uploads/2014/12/testimonials-3.jpg" alt="testimonials-3" width="700" height="473" /><br />
We will be creating a Testimonials section using &#8220;Post Types&#8221; and &#8220;Custom Fields&#8221; which will work in any self hosted WordPress. Note that you may need a little bit of PHP and CSS skills.</p>
<h6>The Problem with a Static Page:</h6>
<p>The biggest issue I have with the static page is that you can&#8217;t use these entries in any other part of the site. For example, we have a small widget in our homepage that shows just a single testimonial. That means we have to duplicate these puppies in the static page and the homepage. Another problem is that each time you need to need to add an entry &#8211; the page becomes longer and longer. Pagination becomes a bit crazy. I guess you can use &#8220;Next Page&#8221; shortcodes &#8211; but still, a bit archaic. Lastly, it is quite cumbersome adding paragraphs and editing HTML for each entry.<br />
Enter &#8220;Post Types&#8221;.</p>
<h6>Why &#8220;Post Types&#8221; and &#8220;Custom Fields&#8221;</h6>
<p>Creating your own Post types offer so many advantages. The most obvious is that you can continue to use the familiar WordPress &#8220;Add New&#8221; and &#8220;Edit Post&#8221; interfaces &#8211; whenever adding a new entry. This is because they <i>ARE</i> the same as your regular &#8220;Posts&#8221; &#8211; just a different &#8220;type&#8221;.<br />
Another advantage is that you can define almost every element of this new Post Type such as a custom slug, exclude it from the menu, exclude it from search, have it&#8217;s own archive and single templates &#8211; almost every custom feature is definable. Read the <a href="http://codex.wordpress.org/Post_Types">WordPress docs</a> for more information on these custom attributes.<br />
Custom fields on the other hand, are key / value pairs we can use for each of our testimonials. In our case, we would need a &#8220;client&#8221; and a &#8220;company&#8221;. We will also make it real user friendly by creating &#8220;Meta Boxes&#8221; for them. You&#8217;ll see what I mean as we dive deeper. So are you ready to get started?<br />
Let&#8217;s begin.</p>
<h3>Step 1) Create the &#8220;Testimonials&#8221; Post Type</h3>
<p>First step is to edit your current theme&#8217;s functions.php file. If it doesn&#8217;t have one, you need to create it and place it in your theme&#8217;s root folder. A functions.php file is the default file that stores all of your theme&#8217;s PHP functions. Add the code below, and I&#8217;ll explain what it does right after.</p>
<pre>function create_posttype() {
  $args = array(
    'labels' =&gt; array(
      'name' =&gt; __('Testimonials'),
      'singular_name' =&gt; __('Testimonials'),
      'all_items' =&gt; __('All Testimonials'),
      'add_new_item' =&gt; __('Add New Testimonial'),
      'edit_item' =&gt; __('Edit Testimonial'),
      'view_item' =&gt; __('View Testimonial')
    ),
    'public' =&gt; true,
    'has_archive' =&gt; true,
    'rewrite' =&gt; array('slug' =&gt; 'testimonials'),
    'show_ui' =&gt; true,
    'show_in_menu' =&gt; true,
    'show_in_nav_menus' =&gt; true,
    'capability_type' =&gt; 'page',
    'supports' =&gt; array('title', 'editor', 'thumbnail'),
    'exclude_from_search' =&gt; true,
    'menu_position' =&gt; 80,
    'has_archive' =&gt; true,
    'menu_icon' =&gt; 'dashicons-format-status'
    );
  register_post_type('testimonials', $args);
}
add_action( 'init', 'create_posttype');
</pre>
<p>The meat of the above code is the &#8220;register_post_type&#8221; method. This function takes 2 arguments, the name of your Post type, as well as an array of settings that you can use to tweak your post type. As you can see, we are assigning a custom slug to the &#8220;rewrite&#8221; key, as well as excluding it from search results through the &#8220;exclude_from_search&#8221; key. For a detailed explanation of the settings you can use, consult the <a href="http://codex.wordpress.org/Function_Reference/register_post_type">WordPress API</a>.<br />
Save your functions.php and log in to the admin. You will see a &#8220;Testimonials&#8221; section appears in the left menu. Go ahead and add some entries and you should see your testimonials fill up the right side &#8211; similar to &#8220;posts&#8221;.<br />
<img decoding="async" class="alignnone noborder size-full wp-image-4248" src="https://michaelsoriano.com/wp-content/uploads/2014/12/testimonials-1.jpg" alt="testimonials-1" width="693" height="497" /><br />
By now you should already see how powerful this type of functionality is. Let&#8217;s continue to the next step and add Meta Boxes for the needed Custom Fields.</p>
<h3>Step 2) Create the Custom Fields / Meta Boxes</h3>
<p>As mentioned before, we need a &#8220;Client Name&#8221; and &#8220;Company&#8221; field &#8211; to add to each of our testimonial. This is easily done through &#8220;Custom Fields&#8221;. But the default WordPress implementation is a bit tacky &#8211; so we need a better way of presenting it: this is done through &#8220;Meta Boxes&#8221;.<br />
Let&#8217;s add the code below to our functions.php file:</p>
<pre>function my_add_meta_box(){
    add_meta_box( 'testimonial-details', 'Testimonial Details', 'my_meta_box_cb', 'testimonials', 'normal', 'default');
}
function my_meta_box_cb($post){
    $values = get_post_custom( $post-&gt;ID );
    $client_name = isset( $values['client_name'] ) ? esc_attr( $values['client_name'][0] ) : "";
    $company = isset( $values['company'] ) ? esc_attr( $values['company'][0] ) : "";
    wp_nonce_field( 'testimonial_details_nonce_action', 'testimonial_details_nonce' );
    $html = '';
    $html .= '<label>Client Name</label>';
    $html .= '<input id="client_name" style="margin-top: 15px; margin-left: 9px; margin-bottom: 10px;" name="client_name" type="text" value="'. $client_name .'" />
';
    $html .= '<label>Company</label>';
    $html .= '<input id="company" style="margin-left: 25px; margin-bottom: 15px;" name="company" type="text" value="'. $company .'" />';
    echo $html;
}
function my_save_meta_box($post_id){
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return;
    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['testimonial_details_nonce'] ) || !wp_verify_nonce( $_POST['testimonial_details_nonce'], 'testimonial_details_nonce_action' ) ) return;
    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;
    if(isset( $_POST['client_name'] ) )
        update_post_meta( $post_id, 'client_name', $_POST['client_name']);
    if(isset( $_POST['company'] ) )
        update_post_meta( $post_id, 'company', $_POST['company']);
}
add_action( 'add_meta_boxes', 'my_add_meta_box' );
add_action( 'save_post', 'my_save_meta_box' );
</pre>
<p>So to explain the code above, we create three new functions. The first two are setting up the input fields. Function &#8220;my_add_meta_box()&#8221; is simply a wrapper for &#8220;add_meta_box()&#8221; which takes several parameters such as the title of the meta box, display name, the call back function (the other function), the post type etc.<br />
The callback function my_meta_box_cb() is the HTML we output in our form. If you read carefully &#8211; it&#8217;s creating the labels and input fields, along with it&#8217;s default values and simply echoing it. Next is actually saving the values to the database.<br />
We have my_save_meta_box(), which does several checks and exits if it doesn&#8217;t meet our requirements. Then we update / save through update_post_meta() methods.<br />
Finally, we have a couple of actions &#8211; which hooks our functions to the WordPress internal methods.<br />
Go ahead and click on a testimonial to edit. Notice our nicely formed meta boxes:<br />
<img decoding="async" class="alignnone noborder size-full wp-image-4249" src="https://michaelsoriano.com/wp-content/uploads/2014/12/testimonials-2.jpg" alt="testimonials-2" width="693" height="550" /><br />
Let&#8217;s set a featured image on a testimonial by setting a post thumbnail. Note that your theme has to support this feature in order for the &#8220;Featured Image&#8221; box to appear. Also, see in our code above that we are setting &#8220;thumbnail&#8221; as one of the values in the &#8220;supports&#8221; key &#8211; which adds this functionality to our post type.<br />
Again, consult the WordPress API for more information on <a href="http://codex.wordpress.org/Post_Thumbnails">enabling post thumbnails</a> in your theme.</p>
<h3>Step 3) Create the Output: The Testimonial Archive</h3>
<p>Now we&#8217;re getting to the fun part &#8211; presenting our data. Our company needs a running list of testimonials, along with the author thumbnail, name and company. So we&#8217;re jumping straight to this view (we&#8217;re not going to worry about the single view since it&#8217;s not necessary in our case).<br />
Create a new file in your theme folder and call it &#8220;archive-testimonials.php&#8221;. Add the following loop inside your new file.</p>
<pre><!--?php if (have_posts()) : ?-->
<!--?php while (have_posts()) : the_post(); ?--></pre>
<div class="testimonial-wrap"></div>
<p>Note that the above code is just for the &#8220;<a href="http://codex.wordpress.org/The_Loop">loop</a>&#8221; of your file. You need to add the other template tags such as getting the header and footer etc. The above is the same as any other loop in WordPress. The only way that it knows how to grab the &#8220;testimonials&#8221; is through the file name &#8220;archive-testimonials.php&#8221;.</p>
<h6>The styling for our Markup above</h6>
<p>Now to achieve our round author thumbnails and containers, we need to add some CSS Magic. In your theme&#8217;s CSS file (usually called styles.css), append the code below:</p>
<pre>.post-type-archive-testimonials h1 {
    color: #21486f;
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 700;
    margin-top:35px;
    margin-bottom:35px;
}
.post-type-archive-testimonials .testimonial-wrap {
    clear:both;
    min-height: 120px;
    background:#F7F7F7;
    margin-bottom:25px;
    padding:25px 35px 30px 70px;
    margin-left:60px;
    border-radius:6px;
    border:1px solid #E7E7E7;
}
.post-type-archive-testimonials .client-photo{
    float:left;
    width:100px;
    height:100px;
    border:6px solid #fff;
    border-radius:50%;
    box-shadow:1px 1px 5px #A8A7A7;
    position: absolute;
    left: 23px;
}
.post-type-archive-testimonials h2.post-title,
.post-type-archive-testimonials .client_name{
    color:#579241;
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 900;
    margin-top:0;
}
.post-type-archive-testimonials .company {
    font-family:verdana;
    font-size:11px;
    color:#000;
}
.post-type-archive-testimonials .post-excerpt {
    margin-bottom:0;
}
.post-type-archive-testimonials .testimonial-wrap .post-excerpt p {
    color:#838383;
}
</pre>
<p>As you can see from our code above, each CSS rule is prefixed by &#8220;post-type-archive-testimonials&#8221;. This is default behavior by WordPress, which is to append this class to the archive page of your custom Post type. This is very useful especially if you want to organize your CSS files efficiently.<br />
This also opens up many possibilities including writing your CSS in an Object Oriented fashion. But that&#8217;s an entirely different topic.<br />
Save your css file and navigate to your http://yoursite.com/testimonials. You should see our HTML and styles in full effect.<br />
Let&#8217;s move on to creating a custom widget to show in different parts of our page such as the homepage.</p>
<h3>Step 4) Create a Homepage Widget</h3>
<p>So now we have data. We are successfully display them it a running list &#8211; which is the main &#8220;testimonials&#8221; page. Now we can use that same list &#8211; and display it in other sections of our site. I&#8217;ve seen this implemented in the sidebar, but in our case &#8211; we&#8217;re putting it in our homepage (since we&#8217;re using a custom home page template).<br />
Now I know I mentioned &#8220;widget&#8221;, but I&#8217;m not really going to build an actual WordPress widget &#8211; which you can reuse anywhere in your site (which is the best way to do it by the way). But for the sake of this tutorial &#8211; which is getting too long, I&#8217;m simply going to output it in the page.<br />
For a tutorial on how to <a href="https://michaelsoriano.com/wordpress-widget-custom-post-types/">create a WordPress widget</a> based on your Post Type &#8211; I have a separate tutorial for that.<br />
Now, in your homepage template (or sidebar, footer etc) &#8211; paste the following code:<br />
The code above is simply HTML with a combination of PHP. The meat of this code is WP_Query() &#8211; which is a WordPress class that deals with special queries to the database. In our case, we want our post type &#8220;testimonials&#8221;, we only want 1 and we want the order to be &#8220;random&#8221;.<br />
Note the $args array that sets up all of those requirements. Then we create an object called $testimonilas from the WP_Query() class &#8211; which we then execute like a normal WordPress loop.</p>
<h6>Styles for our widget</h6>
<p>Now that we have our widget that pulls just a single testimonial, we also want this presented it a different way than our archive page. Let&#8217;s paste the code below into our CSS file:</p>
<pre>.testimonial-home h6 {
    background:#003658;
    border-radius:6px 6px 0 0;
    padding:12px 0 12px 20px;
    margin:0 0 0 20px;
    text-shadow:1px 1px 0 #000;
       color: #C4D8BC;
}
.testimonial-home h6 a {
     color: #C4D8BC;
}
.testimonial-home-inner {
    background:#F0F3F5;
    padding:35px 60px 42px 94px;
    border-radius:0 0 6px 6px;
    margin-left:20px;
    position:relative;
}
.testimonial-home-inner img {
    position:absolute;
    left:-30px;
    top:25px;
}
.testimonial-home-inner p {
    font-size:16px;
    line-height:24px;
    font-style:italic;
}
.testimonial-home-inner .client-photo{
    float:left;
    width:100px;
    height:100px;
    border:6px solid #fff;
    border-radius:50%;
    box-shadow:1px 1px 5px #A8A7A7;
}
.testimonial-home-inner p {
     color:#838383;
}
.testimonial-home-inner p.client_name {
    color:#579241 !important;
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 900;
    font-style:normal;
    margin-bottom:0;
}
.testimonial-home-inner p.company {
    color:#000 !important;
    font-family:verdana;
    font-size:11px;
    font-style:normal;
    line-height: 16px;
}
</pre>
<p>Save your CSS file and view your site homepage (or wherever you plugged the widget code in). If all is successful, you should see a box like below:<br />
<img decoding="async" class="noborder alignnone size-full wp-image-4251" src="https://michaelsoriano.com/wp-content/uploads/2014/12/testimonials-4.jpg" alt="testimonials-4" width="596" height="421" /><br />
Note that the heading for this widget links to our &#8220;testimonials&#8221; archive page. Also, you also need to consider making them responsive by using a solid framework such as <a href="https://michaelsoriano.com/exploring-the-bootstrap-3-0-grid-system/">Bootstrap</a>.</p>
<h3>Conclusion</h3>
<p>I think that covers it. We now have a working system on adding new testimonials to our company site. Now this task can be assigned to the editors of the site. All they have to do is add new entries &#8211; as if they were adding posts (which they&#8217;re already familiar with).<br />
Oh, I almost forgot &#8211; the thumbnails for the client faces have to be a square. This is to make the perfect round shape &#8211; and make sure their faces are in the middle.</p>
<p>The post <a href="https://michaelsoriano.com/create-a-testimonials-section-for-your-wordpress-site-the-right-way/">Create a Testimonials section for your WordPress site &#8211; the Right Way!</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/create-a-testimonials-section-for-your-wordpress-site-the-right-way/feed/</wfw:commentRss>
			<slash:comments>41</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s make a WordPress Widget that displays our Custom Post Types</title>
		<link>https://michaelsoriano.com/wordpress-widget-custom-post-types/</link>
					<comments>https://michaelsoriano.com/wordpress-widget-custom-post-types/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 23 Aug 2013 03:38:10 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3529</guid>

					<description><![CDATA[<p>So I had a question from one my readers: &#8220;How can I add a Latest Listing widget in the sidebar&#8220;, which really translates to &#8220;How do we create a WordPress Widget?&#8221; Well, a widget that pulls our Custom Post Types. So I did a bit of research, and it turns out &#8211; that it&#8217;s not [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-widget-custom-post-types/">Let&#8217;s make a WordPress Widget that displays our Custom Post Types</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So I had a question from one my readers: &#8220;<em>How can I add a Latest Listing widget in the sidebar</em>&#8220;, which really translates to &#8220;<em>How do we create a WordPress Widget</em>?&#8221; Well, a widget that pulls our Custom Post Types. So I did a bit of research, and it turns out &#8211; that it&#8217;s not hard at all. We just need to know the basics of the <a href="http://codex.wordpress.org/Widgets_API">Widgets API</a>, plus a bit of PHP.<br />
This tutorial was written using <a href="http://fearlessflyer.com/manage-your-listings-with-realty-theme">Realty</a>, since it&#8217;s already using Custom Post Types for the House Listings. So I am trying to shoot 3 birds in one stone: 1) To answer my reader&#8217;s question, 2) to add some functionality to the theme, as well as 3) learn something new. Oh and to write this tutorial &#8211; I guess that would be 4 birds then.<br />
So ready to start coding? Also keep in mind that this will work with regular posts &#8211; not just custom post types. You will see what I&#8217;m talking about as we dive deeper. Let&#8217;s begin.</p>
<h6>Create the basic Widget</h6>
<p>In your functions.php file, write the following code:</p>
<pre>class Realty_Widget extends WP_Widget{
function __construct() {
	parent::__construct(
		'realty_widget', // Base ID
		'Realty Widget', // Name
		array('description' =&gt; __( 'Displays your latest listings. Outputs the post thumbnail, title and date per listing'))
	   );
}
function update($new_instance, $old_instance) {
	$instance = $old_instance;
	$instance['title'] = strip_tags($new_instance['title']);
	$instance['numberOfListings'] = strip_tags($new_instance['numberOfListings']);
	return $instance;
}
} //end class Realty_Widget
register_widget('Realty_Widget');
</pre>
<p>The above code sets up our widget class. It&#8217;s extending an already built class &#8211; called WP_Widget, which have methods that we need to override. These methods are: update(), form() and widget(). Don&#8217;t worry if you don&#8217;t know what that means exactly. It&#8217;s just the rules of creating widgets.<br />
Now, notice above that we have a method __construct() &#8211; which just register&#8217;s our widget id, a name and a description. We overrode another method update() &#8211; which just makes ensures that we&#8217;re passing the right values to our $instance array (also makes sure we&#8217;re using the correct calculated instance).<br />
So all we need to create is 2 more methods: form() and widget(). Let&#8217;s take care of that next.</p>
<h6>The form() method</h6>
<p>The method form() builds the form that we have in the admin section. What we&#8217;re building is a very simple form with 2 fields: a text field for the Widget title, and a drop down list for the number of listings we want to show:</p>
<pre>function form($instance) {
	if( $instance) {
		$title = esc_attr($instance['title']);
		$numberOfListings = esc_attr($instance['numberOfListings']);
	} else {
		$title = '';
		$numberOfListings = '';
	}
</pre>
<p><em>[code above has been truncated &#8211; due to syntax highlighting error]</em><br />
We can now also save this widget &#8211; because we have an update() method. Notice that our title and selection saves on click. Now let&#8217;s move to the widget() method.</p>
<h6>The widget() method</h6>
<p>This is the method that actually outputs our widget. This method accepts a couple of arguments &#8211; one of them is our $instance array.</p>
<pre>function widget($args, $instance) {
	extract( $args );
	$title = apply_filters('widget_title', $instance['title']);
	$numberOfListings = $instance['numberOfListings'];
	echo $before_widget;
	if ( $title ) {
		echo $before_title . $title . $after_title;
	}
	$this-&gt;getRealtyListings($numberOfListings);
	echo $after_widget;
}
</pre>
<p>One thing to note is the <strong>$before_widget</strong> and <strong>$after_widget</strong> variables. These are, markups that appear &#8211; you guessed it: before and after the widget. You will also see <strong>$this-&gt;getRealtyListings()</strong> &#8211; which we&#8217;ll cover next.</p>
<h6>Pull our Custom Posts</h6>
<p>This method will do a query of our custom posts. It will only return the number of posts that we&#8217;ve saved in our widget. Add this code to our class:</p>
<pre class="">function getRealtyListings($numberOfListings) { //html
	global $post;
	add_image_size( 'realty_widget_size', 85, 45, false );
	$listings = new WP_Query();
	$listings-&gt;query('post_type=listings&amp;posts_per_page=' . $numberOfListings );
	if($listings-&gt;found_posts &gt; 0) {
</pre>
<p class=""><em>[code above has been truncated &#8211; due to syntax highlighting error]</em></p>
<p>So we have the above code which takes 1 parameter: $numberOfListings. We do an <a href="http://codex.wordpress.org/Function_Reference/add_image_size">add_image_size()</a> so we can get a custom size for our thumbnails. Also note where we&#8217;re querying the post_type of &#8220;listings&#8221;, you can change this value to your own post type (or not even use it for default).<br />
The code then continues building the HTML output of list items containing our post thumbnail, title and date added.</p>
<h6>Add some CSS</h6>
<p>Our CSS is pretty straightforward, just keeping the elements in the right place. You also might want to use your own styles, so I&#8217;ll just post the code that I used, without further explanation.</p>
<pre>.noThumb{
  width:85px;
  height:45px;
  background-color:#000;
  float:left;
  margin:0 12px 0 0;
}
ul.realty_widget {
  margin-top:10px;
}
ul.realty_widget li {
  margin:0 0 15px 0;
  list-style:none;
  min-height:45px;
  line-height:19px;
}
ul.realty_widget li img{
  float:left;
  margin:0 12px 0 0;
}
ul.realty_widget li a {
  font-weight:bold;
}
ul.realty_widget li span {
  display:block;
  font-size:11px;
}
</pre>
<p>So with the above styling, our final output looks like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5703" src="https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1.jpg" alt="widget-tut2" width="512" height="505" srcset="https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1.jpg 512w, https://michaelsoriano.com/wp-content/uploads/2013/08/widget-tut2-1-300x296.jpg 300w" sizes="(max-width: 512px) 100vw, 512px" /></p>
<h6>Conclusion</h6>
<p>So there you have it. We have added a widget to our WordPress theme that pulls our custom post types. As mentioned, this technique will work with regular posts as well. I have updated the Realty theme files to include this code &#8211; so you can go ahead and <a href="https://app.box.com/s/ozy8oczmb6erqqjrijtq">download</a> it if you like. Please let me know in the comments if this tutorial helped your development in any way.</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-widget-custom-post-types/">Let&#8217;s make a WordPress Widget that displays our Custom Post Types</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-widget-custom-post-types/feed/</wfw:commentRss>
			<slash:comments>23</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create an Advanced Search Form for WordPress</title>
		<link>https://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/</link>
					<comments>https://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 09 Oct 2012 21:06:33 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=2788</guid>

					<description><![CDATA[<p>So you want to learn how they do those pretty slick WordPress search forms. The ones that have drop downs of categories, filtering through your posts as soon as you press submit. These are most often used in advanced themes such as eCommerce, job posting and real estate themes. These search forms are a real [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/">How to Create an Advanced Search Form for WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So you want to learn how they do those pretty slick WordPress search forms. The ones that have drop downs of categories, filtering through your posts as soon as you press submit. These are most often used in advanced themes such as eCommerce, job posting and real estate themes. These search forms are a real nice addition to your site &#8211; making it more usable and user friendly.<br />
<img decoding="async" class="alignnone noborder size-full wp-image-2920" title="Chrome PSD" src="https://michaelsoriano.com/wp-content/uploads/2012/10/form.jpg" alt="" width="450" height="450" /><br />
I&#8217;m going to assume that you are pretty well versed in WordPress theme development. I&#8217;m also going to assume that you know what <a href="https://codex.wordpress.org/Post_Types">custom post types</a> are, and know how to create them. I&#8217;m also assuming that you know what <a href="http://codex.wordpress.org/Taxonomies">taxonomies</a> are. These two things are crucial to our form. Without them, we don&#8217;t have much to work with.<br />
So ready to get started? Let&#8217;s roll up our sleeves and begin.</p>
<h3>Build the Form</h3>
<p>As I&#8217;ve mentioned, we are working with custom post types and taxonomies. For this tutorial, we are working with a post type named &#8220;Listings&#8221;. We have also attached several taxonomies to this post type &#8211; named: &#8220;<em>Type</em>&#8220;, &#8220;<em>Rooms</em>&#8220;, &#8220;<em>Area</em>&#8221; and &#8220;<em>Price</em>&#8220;.<br />
As you can imagine, a Real Estate website will have visitors who wish to search through your listings that match only the ones that are &#8220;<em>Single Family</em>&#8220;, &#8220;<em>3 Bedrooms</em>&#8220;, in &#8220;<em>Chicago, IL</em>&#8221; and &#8220;<em>under $100,000</em>&#8220;.<br />
So you see how this can be real handy.<br />
<img decoding="async" class="alignnone noborder size-full wp-image-2921" style="margin-left: 50px;" title="custom-post-type" src="https://michaelsoriano.com/wp-content/uploads/2012/10/custom-post-type.jpg" alt="" width="450" height="390" /><br />
So first we write a function that will return html. Let&#8217;s use WordPress function <a href="http://codex.wordpress.org/Function_Reference/get_terms">get_terms()</a> to populate our select tags. In your functions.php, add the code below:<br />
<script src="https://gist.github.com/michaelsoriano/69dcdbd5a5887b7da9d2.js"></script><br />
The above function will run <strong>get_terms()</strong> on the Taxonomy passed, and will return several option tags with the term slug and name in it. So in your template (where you want your form to appear), create a form and use the function we just created.<br />
<script src="https://gist.github.com/michaelsoriano/66528f1f2308fb43df49.js"></script><br />
Test your form and see your drop down lists populate with the right Taxonomy terms. If not, make sure you&#8217;ve added the right terms for each Taxonomy in your blog.<br />
Also note the form action &#8220;<em>/listing-search-results/</em>&#8220;. This is a page we have yet to build &#8211; one that will handle the form processing. We will cover that in the next section.</p>
<h3>The Processing</h3>
<p>You will need to create a page template &#8211; name it &#8220;<em>Custom Search Results</em>&#8220;. For information on how to create page templates for your theme, click <a href="http://codex.wordpress.org/Pages">here</a>. Now, on this page &#8211; start with the code below:<br />
<script src="https://gist.github.com/michaelsoriano/c700a26f52eb7e1d7014.js"></script><br />
The code above creates two empty arrays. <strong>$item</strong> is filled up with each $_POST key and value, and added to the <strong>$list</strong> array. <strong>$cleanArray</strong> is a merge with &#8220;relation&#8221; key with value &#8220;AND&#8221; to our existing $list array.<br />
So once a user selects items from our drop down lists and submits the form, it should supply the values needed for our arrays. Do a print_r() on the $cleanArray and the output should be similar to below:<br />
<script src="https://gist.github.com/michaelsoriano/05df0b8db27f70e235e4.js"></script><br />
Now we have enough to query our database with. Add the lines of code below:<br />
<script src="https://gist.github.com/michaelsoriano/c5687298965bfb1818bc.js"></script><br />
The above code sets up a few more variables. These are the needed arguments we need to pass into the WP_Query object &#8211; which does all the querying.<br />
As you see, we&#8217;re querying post_type &#8220;listings&#8221; and returning only 9 items. &#8220;paged&#8221; is needed for pagination to work, and the main argument &#8220;<strong>tax_query</strong>&#8221; &#8211; tells the object to query taxonomies. Also note that inside WP_Query is plenty of data sanitation &#8211; so data is clean once passed.</p>
<h3>The Output</h3>
<p>So once data is sent to the WP_Query object, all we need to do is loop through it and display the output. Our WP_Query object (now $the_query) has all the methods to produce the needed results. Add the code below:<br />
<script src="https://gist.github.com/michaelsoriano/fe883e347467eca53b2d.js"></script><br />
The code above behaves like a normal WordPress loop. So insert regular template tags inside the &#8220;while&#8221; loop and your output should render. Notice the use of post navigation (next_posts_link) in the bottom of the code? It should behave like normal posts pagination in WordPress.<br />
<div id="attachment_2923" style="width: 460px" class="wp-caption alignnone"><img decoding="async" aria-describedby="caption-attachment-2923" class="size-full wp-image-2923" title="results" src="https://michaelsoriano.com/wp-content/uploads/2012/10/results.jpg" alt="" width="450" height="390" /><p id="caption-attachment-2923" class="wp-caption-text">Our results page with formatting etc.</p></div></p>
<h3>Conclusion</h3>
<p>There you have it. An advanced search form that will filter through your custom post types. You can display this search form in any part of your website &#8211; ideally in your sidebar or header area. I especially like this treatment because it highlights your custom post type all the more. Making it really stand out from your regular blog posts.</p>
<h6>Useful Resources:</h6>
<p>Make sure you go through these links to better understand what the code above does.</p>
<ol>
<li><a href="http://codex.wordpress.org/Class_Reference/WP_Query">WordPress Codex &#8211; WP_Query</a></li>
<li><a href="http://ottopress.com/2010/wordpress-3-1-advanced-taxonomy-queries/">Advanced Taxonomy Queries &#8211; Ottopress</a></li>
<li><a href="http://wordpress.stackexchange.com/questions/38361/advanced-search-form-with-filters-for-custom-taxonomies-and-custom-fields">Advanced Search Form Filters &#8211; WPAnswers</a></li>
</ol>
<p>The post <a href="https://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/">How to Create an Advanced Search Form for WordPress</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-create-an-advanced-search-form-for-wordpress/feed/</wfw:commentRss>
			<slash:comments>146</slash:comments>
		
		
			</item>
		<item>
		<title>How to automate the WordPress Guest Posting Process</title>
		<link>https://michaelsoriano.com/automating-the-guest-post-process/</link>
					<comments>https://michaelsoriano.com/automating-the-guest-post-process/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sun, 11 Apr 2010 19:05:53 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Tutorials]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=1346</guid>

					<description><![CDATA[<p>Ever wonder how to convert your WordPress blog into a more automated posting process? One that can accept guest posts, job listings or even a forum-type of blog? Where users can submit a post, save it into your drafts section and all you have to do is approve or deny? The beauty of the open [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/automating-the-guest-post-process/">How to automate the WordPress Guest Posting Process</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Ever wonder how to convert your WordPress blog into a more automated posting process? One that can accept guest posts, job listings or even a forum-type of blog? Where users can submit a post, save it into your drafts section and all you have to do is approve or deny? The beauty of the open source community is that someone, somewhere had already thought about doing this, and have already developed a solution. With a combination of several plugins and some custom styling, here is how I was able to automate the guest post submission process here in my blog:<br />
First thing you have to do is check the “<strong>Anyone can Register</strong>” option under “Settings” &gt; “<strong>General</strong>”. Don’t forget to leave the “<strong>New User Default Role</strong>” as “<strong>Subscriber</strong>”.<br />
<img decoding="async" class="alignnone size-full wp-image-1347" title="Enabling the Anyone can Register Option" src="https://michaelsoriano.com/wp-content/uploads/2010/04/auto-1.jpg" alt="" width="576" height="100" /></p>
<h3>Lock Down the Registration Process</h3>
<p>Now that you have your site open for registration, it is best that you install these plugins first to enable tighter security:<br />
<strong><a href="http://bueltge.de/wordpress-login-sicherheit-plugin/652/">Secure WP</a></strong> – as many options that this plugin comes with to enhance security, what I especially need it for is to disable the error messages at login (which this plugin does very well)<br />
<strong><a href="http://didier.lorphelin.free.fr/blog/index.php/wordpress/sabre/">SABRE</a></strong> &#8211; stands for “Simple Anti Bot Registration Engine”. This produces that image during registration to block “autobots”.<br />
<strong><a href="http://devel.kostdoktorn.se/limit-login-attempts">Limit Login Attempts</a></strong> – the plugin title says it all. Activate this plugin and tweak depending how tight you want login attempts. Note that you’re not going to see any error messages due to the Secure WP plugin.</p>
<h3>Hide the WP Admin Panel</h3>
<p>So registration is open, security is tight – you still don’t want users to see your WordPress admin area. Not that there’s anything wrong with that – but it just looks more sophisticated when all is done in the front end. Install the following plugins:<br />
<strong><a href="http://www.jfarthing.com/wordpress-plugins/theme-my-login-plugin">Theme My Login</a></strong> &#8211; this plugin will generate a page called “<strong>Login</strong>” – this is where your new login forms (includes new registration and forgot password) will sit. Additional options also include custom emails, redirection and moderation. *Make sure you check “<strong>Enable Template Tag</strong>” under “<strong>Optimization</strong>” – You’ll need this in your theme later.<br />
<img decoding="async" class="alignnone size-full wp-image-1352" title="Theme My Login Settings" src="https://michaelsoriano.com/wp-content/uploads/2010/04/theme-my-login.jpg" alt="" width="576" height="320" /><br />
<strong><a href="http://www.jfarthing.com/wordpress-plugins/theme-my-profile-plugin">Theme My Profile</a></strong> – plugin created by the same author, which ports the users “profile” page into the front end. Make sure you theme and block admin area ONLY for roles you want.<br />
The following screenshots show the login page, as well as the profile page generated by the plugins that I’ve mentioned:<br />
<img decoding="async" class="alignnone size-full wp-image-1353" title="The New Registration Form" src="https://michaelsoriano.com/wp-content/uploads/2010/04/registration.jpg" alt="" width="576" height="520" /><br />
<img decoding="async" class="alignnone size-full wp-image-1350" title="The Themed User Profile Page" src="https://michaelsoriano.com/wp-content/uploads/2010/04/profile.jpg" alt="" width="576" height="520" /></p>
<h3>TDO Mini Forms</h3>
<p>We’ve come to the meat of the project. This is the plugin that does all the magic. <a href="http://thedeadone.net/download/tdo-mini-forms-wordpress-plugin/">TDO Mini Forms</a> allows users (registered on not registered) to submit and edit posts to your blog. It comes with its form creator that lets you design the post submission form any way you want. Widgets that let you drag and drop components into your form, as well as a form “<strong>hacker</strong>” that allows even deeper code tweaking. What I especially liked is that it hooks up with your “<strong>Akismet</strong>” for spam protection.<br />
<img decoding="async" class="alignnone size-full wp-image-1354" title="TDO Mini Forms Configuration Page" src="https://michaelsoriano.com/wp-content/uploads/2010/04/tdo-mini-forms-1.jpg" alt="" width="576" height="520" /><br />
After specifying all the configuration settings with TDO, go ahead and create a form with “Form Creator”. The form creator is a somewhat decent drag and drop interface where you grab the widgets in the bottom and drag it to the form. Widget settings are applied by clicking on the settings tab and it brings up the settings window as shown below:<br />
<img decoding="async" class="alignnone size-full wp-image-1355" title="Form Creator by TDO" src="https://michaelsoriano.com/wp-content/uploads/2010/04/tdo-mini-forms-2.jpg" alt="" width="576" height="520" /><br />
Once you’ve decided on the fields and the settings, you can now alter the code to change the verbiage, along with adding HTML elements in order to be able to style it in your stylesheet. Below shows my contribute form:<br />
<img decoding="async" class="alignnone size-full wp-image-1356" title="My newly styled Contribute Form" src="https://michaelsoriano.com/wp-content/uploads/2010/04/contribute1.jpg" alt="" width="576" height="520" /></p>
<h5>Maybe some Custom Code</h5>
<p>Depending on your pages – you might need to add some PHP conditional tags and functions to the theme manually. This is to link the new pages to each other. Simply copy your theme’s page.php file and rename it to something.php – convert it into a template by adding the code on top of the page:<br />
<script src="https://gist.github.com/michaelsoriano/0d6382649768d400dd66.js"></script><br />
Now below the call for the content, add the conditional tag with from the Theme My Login plugin:<br />
<script src="https://gist.github.com/michaelsoriano/537d94924b848b9eab1f.js"></script><br />
The screenshot below shows the custom link to the contribute form that we just created:<br />
<img decoding="async" class="alignnone size-full wp-image-1349" title="Custom Link to Contribute" src="https://michaelsoriano.com/wp-content/uploads/2010/04/login.jpg" alt="" width="576" height="220" /><br />
All you have to do now is to wait for guest post submissions and depending on the content &#8211; simply approve, edit or deny. The submissions are saved as draft posts and are in the moderation view of TDO mini forms:<br />
<img decoding="async" class="alignnone size-full wp-image-1367" style="border: 0;" title="The Final Process" src="https://michaelsoriano.com/wp-content/uploads/2010/04/moderation2.jpg" alt="" width="576" height="813" /></p>
<h3>Conclusion</h3>
<p>Now that you have converted your blog into a more automated (and sophisticated) posting process – think of all the possible scenarios you can create. Of course I’m completely aware that my guest posts will not land any successful submissions any time soon – it’s just good to know that it’s available. Not to mention, it was fun to make.</p>
<p>The post <a href="https://michaelsoriano.com/automating-the-guest-post-process/">How to automate the WordPress Guest Posting Process</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/automating-the-guest-post-process/feed/</wfw:commentRss>
			<slash:comments>29</slash:comments>
		
		
			</item>
		<item>
		<title>Embed Videos in your Web Pages with Flowplayer!</title>
		<link>https://michaelsoriano.com/embed-videos-with-flowplayer/</link>
					<comments>https://michaelsoriano.com/embed-videos-with-flowplayer/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 01 Feb 2010 05:39:20 +0000</pubDate>
				<category><![CDATA[Design & UX]]></category>
		<category><![CDATA[flowplayer]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=1231</guid>

					<description><![CDATA[<p>Normally when you want to add videos into your web pages &#8211; automatically you think of Youtube. All you need is a Youtube account, upload your video, embed the code and your ready to go! But what if you want to do something more? Something like changing how the player looks, maybe add a different [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/embed-videos-with-flowplayer/">Embed Videos in your Web Pages with Flowplayer!</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Normally when you want to add videos into your web pages &#8211; automatically you think of Youtube. All you need is a Youtube account, upload your video, embed the code and your ready to go! But what if you want to do something more? Something like changing how the player looks, maybe add a different splash image, take out that annoying “Youtube” logo, and more importantly &#8211; take out that link toYoutube.com. Now there is a better alternative. Enter Flowplayer.</p>
<h3>What is FlowPlayer?</h3>
<p>FlowPlayer is an open source video player for the web. It is a way for you to stream videos in your pages, from your own server. Thus, eliminating the need for external video serving services such as YouTube. FlowPlayer is highly extensible and customizable. Though it may take a little more than a few clicks &#8211; the benefits far outweigh the work needed to get it running. Consider these pros and cons:</p>
<h5>Pros:</h5>
<p><strong>No Links to External Sites</strong> &#8211; As I’ve mentioned, this alone is enough reason to use FlowPlayer. Your visitors cannot escape your website when video is live. They stay in your site during playback and when clicked. In addition, you can configure your player to use custom events (see below)<br />
<strong>CSS Skinning and Branding</strong> &#8211; You can totally change the appearance of Flowplayer. This includes player controls, backgrounds and logo (custom logo is supported in the “Commercial” version). Best of all &#8211; skinning FlowPlayer follows strict web standards using simple HTML and CSS. Check out this demo using a billboard sign as the background of the player: <a href="http://flowplayer.org/demos/skinning/container-background.html. ">http://flowplayer.org/demos/skinning/container-background.html</a>.<br />
<a href="http://flowplayer.org/demos/skinning/container-background.html"><img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2010/01/custom-skin-flowplayer2.jpg" alt="" title="Try Doing This with YouTube" width="576" height="300" class="alignnone size-full wp-image-1247" /></a><br />
<strong>Set your own Splash Image </strong>&#8211; one of the annoying things about Youtube is it automatically selects the splash image for you. With Flowplayer you can select a high quality image as the splash state &#8211; before the actual player loads.<br />
<strong>You can add your own Events </strong>&#8211; configure your player to do more than just playback videos. Examples can be adding captions during playback, extracting clip information as well as chaining video clips to play one after the other. See some examples of events <a href="http://flowplayer.org/documentation/events/">here</a>.<br />
<strong>Extend with Plugins</strong> &#8211; Plugins are already made functionalities that other developers have created and made available for you to download. Examples of kick ass plugins are <a href="http://flowplayer.org/plugins/flash/content.html">Flash Content</a>, <a href="http://flowplayer.org/plugins/javascript/embed.html">Javascript Embed</a> and <a href="http://flowplayer.org/plugins/streaming/slowmotion.html">Streaming Slow Motion</a>.</p>
<h5>Cons:</h5>
<p><strong>Need some HTML experience </strong>&#8211; you will need to touch the source code of your pages to use. For advanced functionality &#8211; scripting technologies such as javascript and flash is also required<br />
<strong>You need to convert the videos locally first before uploading</strong> &#8211; at the time of writing, FlowPlayer supports FLV, H.264 and MP4. You will need to convert your video to the said formats before uploading. Check this article for good information on Flash Video Conversion: <a href="http://worldtv.com/blog/guides_tutorials/flv_converter.php">http://worldtv.com/blog/guides_tutorials/flv_converter.php</a><br />
<strong>Bandwidth</strong> &#8211; Since videos are served locally you may see an increase in bandwidth usage.</p>
<h3>How to use FlowPlayer</h3>
<p>What I really liked about FlowPlayer is their extensive documentation. It includes walkthroughs for beginners, as well as in depth instructions for the expert programmers. To start using FlowPlayer &#8211; all you need is to do the following:<br />
<strong>1) <a href="http://releases.flowplayer.org/flowplayer/flowplayer-3.1.5.zip">Download</a> the FlowPlayer Files</strong> &#8211; This download includes the actual FlowPlayer .swf files as well as the .js file to get you started. It also includes an HTML page that demonstrate the basic installation of FlowPlayer.<br />
<strong>2) Include the flowplayer.js in your HTML:</strong><br />
<script src="https://gist.github.com/michaelsoriano/f98ba34c1d77c1864e7c.js"></script><br />
<strong>3) Setup the player container</strong> &#8211; Simply add an anchor tag with 3 important attributes: a) <em>href &#8211; the pointer to the video file</em>, b) style: <em>determines the size and basic display properties of the player </em>and c) id: <em>very important &#8211; this acts as a selector for the javascript to target to load the player</em>.<br />
<script src="https://gist.github.com/michaelsoriano/5125c89b4bea0d8afcee.js"></script><br />
<strong>4) Install Flowplayer</strong> &#8211; The final code tells FlowPlayer to install in our anchor tag:<br />
<script src="https://gist.github.com/michaelsoriano/e085c00d42d3f205b16d.js"></script></p>
<h3>FlowPlayer and WordPress:</h3>
<p>Oh yes &#8211; you can actually embed Flowplayer inside your posts. The beauty of it is &#8211; there are actually several Flowplayer plugins already available for WordPress. Though I’m just going to cover the two most popular:<br />
<strong><a href="http://foliovision.com/seo-tools/wordpress/plugins/fv-wordpress-flowplayer">FV WordPress Flowplayer </a></strong>&#8211; developed by Foliovision, is a straight forward FlowPlayer plugin made exceptionally easy. All you need is to install, upload your video and add the plugin shortcode to your posts. Note that this is the plugin I’m using for my video demo above. The screenshot below shows the plugin options page:<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2010/01/screenshot-3.png" alt="" title="Screenshot of FolioVisions Options" width="576" height="337" class="alignnone size-full wp-image-1248"  /><br />
<strong><a href="http://www.saiweb.co.uk/wordpress-flowplayer">Flowplayer for WordPress</a></strong> &#8211; created by David Busby of Saiweb, this plugin also includes player customization features as well as commercial license key input for advanced settings:<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2010/01/screenshot-1.png" alt="" title="SaiWebs Options Page" width="576" height="300" class="alignnone size-full wp-image-1249"  /></p>
<h5>Embed FlowPlayer in your Theme:</h5>
<p>If you’re like me, you may come across a website project that requires videos hosted in their own server. Of course WordPress and FlowPlayer is a good combination. What about if the requirements for the player are so extensive that may not be achieved with any sort of plugin? This is when you’d want to embed FlowPlayer in your theme.<br />
The process is pretty much the same as the basic FlowPlayer installation. The only difference is we’re using custom fields for the href attribute of our player. In your theme folder, edit single.php and include this code inside the loop:<br />
<script src="https://gist.github.com/michaelsoriano/b151d86c3d7a3d7bb100.js"></script><br />
This sets up a default player for each post, wrapped in an “if” block. This way you customize the page to your client’s extensive requirements. A screenshot of my page mockup is shown below:<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2010/01/scv-mockup.jpg" alt="" title="Mock Up with Custom Player" width="576" height="300" class="alignnone size-full wp-image-1250" /><br />
Don’t forget the call to install FlowPlayer:<br />
<script src="https://gist.github.com/michaelsoriano/7950a9f8d1f0d0ea90c9.js"></script><br />
Now all you need to do is upload the movie using the default WordPress media uploader, and plug in the url in a custom field set to “<strong>movie</strong>”</p>
<h3>Conclusion</h3>
<p>If you haven’t already noticed &#8211; almost every aspect of FlowPlayer can be customized. Having this much control over video content is invaluable and cannot compare to services like YouTube. Best of all, the basic version is free under the GPL license which you can use for personal or commercial purposes. Note that there are also paid versions that determine the amount of branding you can as well as legal domain usage. Head on over to FlowPlayer&#8217;s <a href="http://flowplayer.org/index.html">website</a> for more information. </p>
<p>The post <a href="https://michaelsoriano.com/embed-videos-with-flowplayer/">Embed Videos in your Web Pages with Flowplayer!</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/embed-videos-with-flowplayer/feed/</wfw:commentRss>
			<slash:comments>26</slash:comments>
		
		
			</item>
	</channel>
</rss>
