menu
Anh-Thi DINH

PhP Wordpress 2: index page

Posted on 24/11/2018, in Web development.

I use this note for all I’ve learned when I build again website math2it.com using Wordpress. Different from Note of Wordpress 1, in this note, I focus on what I will use to build the theme.

settings_backup_restore Back to PHP Wordpress 1.

Include Bootstrap CSS

In WP1, use below codes to apply custom css in folder css. However, I want to insert one time all files in some folder, e.g. bootstrap41, and I wanna use scss instead of css. How can I do those?

function math2itwp_scripts() {
	wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '4.1.3' );
	wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' );
	wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array( 'jquery' ), '4.1.3', true );
}
add_action( 'wp_enqueue_scripts', 'math2itwp_scripts' );
  • For including a folder: NO

SASS with Wordpress

For using scss/sass (I followed this guide):

  1. Install ruby
  2. Update ruby (if you installed it before) and install compass,

     gem update --system
     gem install compass
    
  3. cd to the current wordpress theme
  4. Create a folder named sass in the root of this theme.
  5. Create a file config.rb which contains below codes, this file is for compass

     http_path = "/" #root level target path
     css_dir = "." #targets our default style.css file at the root level of our theme
     sass_dir = "sass" #targets our sass directory
     images_dir = "images" #targets our pre existing image directory
     javascripts_dir = "js" #targets our JavaScript directory
    
     # You can select your preferred output style here (can be overridden via the command line):
     # output_style = :expanded or :nested or :compact or :compressed
    
     # To enable relative paths to assets via compass helper functions.
     # note: this is important in wordpress themes for sprites
    
     relative_assets = true
    
  6. Inside folder sass, create a folder named _partials, all partial scss files will be located in this folder. For example, we use _font.scss to store all styles relating to font for the theme.
  7. Inside folder sass, create a file named style.scss, after every modification, this file will be generated by compass and overwirte the style.css file in the root theme folder. In the content of this file, you place

     @import "compass";
     @import "_partials/font";
    
  8. Use terminal and run following command (suppose that you are already in the theme folder). From this step, everytime you modify style.scss or files in _partials folder, the compass will automatically update the changes and overwrite to the style.css file in root theme folder.

     compass watch
    

Default menu

As default, like in WP1 note, we can create a “menu bar” with already-created pages by

<nav class="blog-nav">
	<a class="blog-nav-item active" href="<?php echo get_bloginfo( 'wpurl' );?>">Home</a>
	<?php wp_list_pages( '&title_li=' ); ?>
</nav>

Manually

However, I wanna create a custom navigation bar in which there are some fields being not a page! I also wanna change the color of each field when it’s chosen.

You can add manually by something like that in the file header.php,

<nav class="navbar navbar-dark nav-bg navbar-custom">
	<div class="container">
		<a class="nav-home" href="<?php echo get_bloginfo( 'wpurl' );?>">
		<i class="icon-home"></i>
			<span>Home</span>
		</a>
		<a class="nav-custom-1" href="<?php echo get_bloginfo( 'wpurl' );?>/custom-1">
			<i class="icon-pi-outline"></i>
			<span>Custom 1</span>
		</a>
		<div class="nav-search">
			// form of search
		</div>
	</div>
</nav>

Add custom menu with additional icon field

But I wanna add some field in wp admin so that I can add some fields in that (intuitively), the code in the header.php is only some lines, they will automatically get the info I provide in wp-admin to show. But how?

  • I wanna add custom link & custom title for that nav.
  • I wanna add custom color for each nav.
  • I wanna add custom icon for each nav.
  • I wanna add custom “other factor” for each nav.

I followed below articles:

  • For create and display a custom menu in WP. For more options, cf wp_nav_menu
  • Use Advanced Custom Fields! (for localhost, download the zip file, extract to a folder and copy it to wp-content/plugins) and follow this instruction to add custom field to menu, like “icon”, and how to display it alongside with other defaut ones.
    1. After install ACF.
    2. Custom Fields (in WP admin) > Add new (field group) > name it Nav custom items
    3. In Add field, add icon for example
    4. In Location, choose Menu item in Show this field group if and then equal to > All
    5. Click on Update
    6. Go back to Appearance > Menus > click on some nav and see the new field “icon”.
  • Next question, how to use this field in the theme?, read this section.
  • Remove all class in li of the menu, follow this article.
  • By default, the menu will have a form like,

      <div class="custom-nav">
          <ul>
              <li>
                  <a>Menu 1</a>
              </li>
              <li>
                  <a>Menu 2</a>
              </li>
              <li>
                  <a>Menu 3</a>
              </li>
          </ul>
      </div>
    
  • Now, we only want below one, just follow this article.

      <a>Menu 1</a>
      <a>Menu 2</a>
      <a>Menu 3</a>
    

Use only one search field file

Use fontello for custom icon font

Instead of using Awesome font, we use fontello for a custom icon font.

  • If you need to crop an image, use this site.
  • Convert that image to svg format, use this site.
  • Use fontello site to convert to font (drag and drop svg file to the site) and then choose the font and download.
  • Create a folder named css/fontello and copy fontello.css in the downloaded zip file to it.
  • Copy font folder in downloaded zip file to css/
  • In functions.php, add

      wp_enqueue_style( 'fontello', get_template_directory_uri() . '/css/fontello/fontello.css' );
    
  • Use <i class="icon-math2it"></i> for the icon where math2it is the name you give to fontello site before you download.

Ad custom color to each category

Using Advanced Custom Field like in section navigation. Note that, we need to choose Taxonomy in Show this field group if.

Get color from WP and update to CSS

I wanna a custom css color will be applied to each nav element. These color are taken from the wp admin database. It means that we can obtain them via a php code. However, it’s difficult to use php code inside a css file. It’s easier if we add “inline code” in <head> like that

<style type="text/css">
	.icon-home:hover{color: #eee;}.icon-tex:hover{color: #fff;}
</style>

In order to get each element of nav by using php,

$menuLocations = get_nav_menu_locations();
$menuID = $menuLocations['<id-of-menu>'];
$primaryNav = wp_get_nav_menu_items($menuID);
foreach ( $primaryNav as $navItem ) {
	$nav_icon = get_field('nav-icon', $navItem); // get icon of each nav
	$nav_color = get_field('nav-color', $navItem); // get color of each nav
	echo '.'.$nav_icon.':hover{color:'.$nav_color.';}';
}

Build custom post layout with settings in WP admin

I wanna build a custom post layout and then use it in many different page layouts. In this layout, firstly, I want,

  1. source of post: where the post from?
  2. number of post: how many posts will be displayed?
  3. post’s properties: which properties of post can be chosen to be showed in this layout?
  4. Flexible positions: left or right big-post in comparison with the other smaller, for example.

References: cat templates codex, query_posts codex, create a custom cat page,

Advanced Custom Fields

The question is how to use fields created by ACF?

Get the latest posts

I wanna build the index page. First I wanna show the latest posts.

  • CF: get latest published posts with title and thumbnail.

      <ul id="slider-id" class="slider-class">
          <?php
          $recent_posts = wp_get_recent_posts(array(
              'numberposts' => 4, // Number of recent posts thumbnails to display
              'post_status' => 'publish' // Show only the published posts
          ));
          foreach($recent_posts as $post) : ?>
              <li>
                  <a href="<?php echo get_permalink($post['ID']) ?>">
                      <?php echo get_the_post_thumbnail($post['ID'], 'full'); ?>
                      //Assuming that the slider support captions 
                      <p class="slider-caption-class"><?php echo $post['post_title'] ?></p>
                  </a>
              </li>
          <?php endforeach; wp_reset_query(); ?>
      </ul>
    
  • WP post object (besides post_title, ID)

      WP_Post Object
      (
          [ID] =>
          [post_author] =>
          [post_date] => 
          [post_date_gmt] => 
          [post_content] => 
          [post_title] => 
          [post_excerpt] => 
          [post_status] =>
          [comment_status] =>
          [ping_status] => 
          [post_password] => 
          [post_name] =>
          [to_ping] => 
          [pinged] => 
          [post_modified] => 
          [post_modified_gmt] =>
          [post_content_filtered] => 
          [post_parent] => 
          [guid] => 
          [menu_order] =>
          [post_type] =>
          [post_mime_type] => 
          [comment_count] =>
          [filter] =>
      )
    
  • Change post-date format to 02-11-2018 for example (cf): replace $post['post-date'] by

      date('n-j-Y', strtotime($post['post_date']));
    

    cf list of format of date

  • Get the category of the post (cf)

      $category_detail = get_the_category('4');//4 is $post->ID
          foreach($category_detail as $cd){
          echo $cd->cat_name;
      }
    
  • If you use Advanced Custum Field to create a new field, e.g. cat-icon, for category, you can access it via

      // give 'cat-icon' for category $ first cat
      $post_cat_icon = get_field('cat-icon', $first_cat[0]);
    

Add custom menu and submenu in WP admin

  • Add menu, cf
  • Add submenu, cf
  • Cf Tania.
  • Ad custom settings with tabs, cf SE

How to call them?

<li><a href="<?php echo get_option('github'); ?>">GitHub</a></li>
<li><a href="<?php echo get_option('twitter'); ?>">Twitter</a></li>
  1. Add new field

     // facebook-group
         add_settings_field(
             'facebook-group', 
             'Facebook Group URL', 
             'site_setting_facebook_group',  // function to call
             'site_setting_option', 
             'site_setting' // sectom id 
         );
    
  2. Register

     register_setting('site_setting_option', 'facebook-group');
    
  3. Callback

     // facebook group
     function site_setting_facebook_group() { ?>
         <input type="text" name="facebook-group" id="facebook-group" value="<?php echo get_option('facebook-group'); ?>" />
     <?php }
    

Includes files in functions.php

In order to manage functions added to functions.php, we need to store each function in to a separated file and then include it in functions.php. Cf SE.

  • Child file, eg css-js.php, stored in /functions-files/
  • Beginning of css-js.php, add <?php
  • In functions.php

      require_once( __DIR__ . '/functions-files/css-js.php');
    

Change seprator between title and tagline

Add to functions.php (cf),

add_theme_support( 'title-tag' );
add_filter( 'document_title_separator', 'cyb_document_title_separator' );
function cyb_document_title_separator( $sep ) {
    $sep = "|";
    return $sep;
}

Add css file for admin panel

Suppose that the admin panel uses /style_admin.css for containing the css. You need to add these lines to functions.php of the theme

function admin_panel_css() {
    wp_enqueue_style( 'style', get_template_directory_uri() . '/style_admin.css' );
}
add_action( 'admin_head', 'admin_panel_css' );

In case you wanna use scss, you can follow this section.

Get posts from specific category

References:

  1. In order to know ID of some category: Posts > Categories > Move your mouse over the category you wanna know its id, look at the bottom of your web browser, they list something like this …wp-admin/term.php?taxonomy=category&tag_ID=1…. The number 1 is the id you are looking for.
  2. Use below code to get posts from this category (cf)

     $args = array(
             'category'         => 1,
             'numberposts' 		 => 5,
             'orderby'          => 'name',
             'order'            => 'ASC',
     );
     $posts = get_posts($args);
    
  3. If you wanna take a specific post with its id or just wanna get a range of post from $post, cf.

Get the first post

Using bool variable to check the first post, cannot use something like $post[0]!!!

$first_post = true;
foreach($cat_posts as $post) : 
	setup_postdata( $post );
	if ($first_post):
		// codes
	endif;
	$first_post = false;
endforeach; wp_reset_postdata();

If you don’t want to use postdata, just use $$post->ID$.

Support SVG image file

Default, SVG is not supported in WP. You need to add following lines to functions.php to active this (cf),

function add_file_types_to_uploads($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_action('upload_mimes', 'add_file_types_to_uploads');
Top