Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views22 pages

Campus

The document outlines the process of creating a custom post type named 'Campuses' in WordPress, including the necessary code modifications and the addition of a Google Maps integration for displaying campus locations. It details the steps for setting up custom fields using the Advanced Custom Fields plugin, obtaining a Google API key, and implementing JavaScript to create an interactive map with markers for each campus. Finally, it explains how to customize the front-end display and link the campuses in the header navigation.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views22 pages

Campus

The document outlines the process of creating a custom post type named 'Campuses' in WordPress, including the necessary code modifications and the addition of a Google Maps integration for displaying campus locations. It details the steps for setting up custom fields using the Advanced Custom Fields plugin, obtaining a Google API key, and implementing JavaScript to create an interactive map with markers for each campus. Finally, it explains how to customize the front-end display and link the campuses in the header navigation.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 22

Create a Custom New Post Type For named Campuses

jumped into mu plugin folder

copy the event post type and event post type 15 or so lines

Change the Words to Campus


// Campus Post type
and actual code name or variable to be campus instead of event
to be singular dont need to be plural

Archive url to be campuses in plural

edit different labels

name should be plural Capitalised

all item also be pluralexcept item whihc is singular

register_post_type('campus', array(
'supports' => array('title', 'editor', 'excerpt'),
'rewrite' => array('slug' => 'campuses'),
'has_archive' => true,
'public' => true,
'labels' => array(
'name' => 'Campuses',
'add_new_item' => 'Add New Campus',
'edit_item' => 'Edit Campus',
'all_items' => 'All Campuses',
'singular_name' => 'Campus'
),
'menu_icon' => 'dashicons-location-alt'
));

we we go to admin page we will see brand new post type campuses

Cool!

Create New Campuses Post

Add New
Title - Downtown West
ContentArea- Dummy Text
SubTitle- A beautiful Campus in the Heart of Downtown

Publish

Add Another New Campuses Post

Add New
Title- Downtown East

University may have 5 or 10 Different Locations through out Town or Cities

so if we have Differnt locations all through out the cities


it would be nice if we have interactive google map

for each one have campus location


in order to pin a location on a map

we just need to more a title of a post or having DUmmy COntent

if we open Down town West

in addition to the title Field and COntent Field

we need a new Custom Field

you cna drap around or Zoom around Google Map and


Click where you want to pin to be

and it will save the latittude and Longitude

in address in your databse

so with the help Avance Custom Field Plugin


click custom field

create new field group named Map Location thas the group name
add new

Now we have to create the Actual field

named map location


for the the field type choice select goole map

reuired yes

fill out the location box -- show this field

select campus

save pubisher

test it out
click on campuses again
lets try edit down otwn west
you map is embeded
but u might got loading error

because you just importing an iframe


points toward the webpage that live on Google Servers

actually we will talk to google service with jaavascript


but to work it roperly we need an API key

What is an API key

stinge of letters and numbers almost a kind of passwords


a kind of secret encryption key
a handshake which we make with google servers

whihc lets us to communicate Google Map Service


for that you need Google API
so u have to obtained API key from Google

https://cloud.google.com/maps-platform/

sighn in to google account


click get a key button
create a new project

named it whatever you want

create and enabl API

*****

AIzaSyDMlqRycPBP47HLNF7_EYYmDQCmRQzovWk
jut passed this key to custom wodpress plugin

now we had a permission to talk with Google Map Service

Go to Functions .php

function universityMapKey($api) {
$api['key'] = 'AIzaSyDMlqRycPBP47HLNF7_EYYmDQCmRQzovWk';
return $api;
}

add_filter('acf/fields/google_map/api', 'universityMapKey');

acf is stands for advance custom field looks in field


we interested in google map api field

we are dealing with api


named the api
which are going to create

so we create the function with that name


i parettheis igve a prameter with dollar sigh and argumentcalled $api
custom plugin which makes dta available to us
now we can use it in the body of our function

letdarget that data or array

look inside that array the property name key


and set that to euual

paste your obtained api key in enclosed quotes


we are still in th body of the function so
then return that api array

pluginns gaves this piece of data work with acf/fields/google_map/api'

we manipulate it with api['key'] = 'AIzaSyDMlqRycPBP47HLNF7_EYYmDQCmRQzovWk';


and we retutn it --return $api;

refresh now you have a google map


search for location

update

***************************************************
Build Campus Map Front End for New CAMPUS POST TYPE
How to display
Campuses link up in the header menu bar connect with
interactive Google map with different pins

Step lets edit the Campuses Link up in the header


to all Campuses Archive Screen
so in order to make that edit lets jumpinto header.php file into our Text Editor

go to header navigation check campus link

Adjust href remove the place holder hastags


drop in php code lets echo out name of the post type campus
<?php echo get_post_type_archive_link('campus'); ?>

and making the link lid up yellow when we on the campus page
target the openong li element
drop in php say
only if and parenthesis for if condition
get_post_type
its a function so its have its own parethesis

only return value of campus


only if it that the case

add a css class


echo out
new code

<li <?php if (get_post_type() == 'campus') echo 'class="current-menu-item"' ?>><a


href="<?php echo get_post_type_archive_link('campus'); ?>">Campuses</a></li>

up in the title bar we see page not found


the problem is whever you register a new post type

save changes the permalink strctr or rebuild or esets permalinks


under general setting back in admin panel

Now Refresh the page click on capus


we are back in business
Cool!

we can see Downtown East and Downtown West


------

this is the post we want to see except we dont want the Formatting we want

when we dealt wih campuses we want fgoogle map pins for each location

in other we need custom templates for this screen


to get our desires look and feel for google campus scree

at the moment this page is powered by archive.php

so if we want a unique template for just campuses


we have to make a new tempalte file

so create a brand new file named is archive-campus.php

save som nay code avoid typing

lets copy the archive.program code into this file


as a starting place and
get some tweaking

change the page banner title ----Our Campuses

and sub title --- we have several convenient locations

Now We Customizing this template instead text box


template
meaning

instead of outpuuting permalink and post


create a map box
we output the addres of each post having latitude and longitude

right after the title and semi colon


create a variable called $mapLocation
ans set is equal to
result of a function named get_field('map_location');
and within the parentheis we just passed an argument
the field name which we gave to crerate in advance custom field

field name we gave is ---- map_location


just a code more readable why dont we

drop a new line right before maplocation

so far we didnt output anything on the screen

we just created the variable


that stores the value
of that Custom Field

before we accessing the taltitude and longitude of th efield


lets answer the Question what is the value lives inside this
get_field('map_location')
is it a sring of text is it numbers an array or object
what is it so what is the data resides in it so
to find that out call the print function name
print_r()
and just passed it the name of the variable
d we named it map_location
code
get_field('map_location');print_r(map_location)

**************cood look stage1


<?php
while(have_posts()) {
the_post(); ?>
<li><a href="<?php the_permalink(); ?>">
<?php the_title();$mapLocation = get_field('map_location');
print_r($mapLocation)?>
</a></li>

<?php }
echo paginate_links();
?>
</ul>

Lets go and svae this and on the front end


right after the title of each post
we have output latitute and longitude
but we dont want to see that result in plain text we want
we wnat to output latitute and longitude for
in a structure that javascript can easily access

because javascript which Communicate with Google map servers

so lets jump back in the text editor


and lets clean up little bit

delete from opening and closing list item so we have

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

// lets create a opening divand closing div tag


// and give a data attribute for latitute lat for latitudeand set that isequal to
x
// and give another data attribute for longitude lng for longitude and set that
isequal to y
// and give a class equal to marker so that javascirpt find thats elemnt
// here we structed things so that javascript can access longitude and latitus
properly

// we are still in the php mode right under the the_post() line
/*so why dont we create the variable that stores th emap field data named
$mapLocation*/

// now just we output latitude and longitud evariable


// instead of output x and y we placed the actual value

// renove the place holder x and y see code stage 3

*******************code stage 2
$mapLocation = get_field('map_location');
<div class= 'marker' data-lat='x' data-lng='y'></div>

<?php }
echo paginate_links();
?>
</ul>

*************************code stage 3
drop in php and echo out map location
of our variable
look inside the array enclosed in square brackets with lat value
and same for longitude

lets echo $mapLocation our variable name look inisde it lat and long value

data-lat=
<?php echo $mapLocation['lat'] ?>"
data-lng="
<?php echo $mapLocation['lng']; ?>"

// we have list item instead of div thats why we have wrapped in ul tags
// but now we have div tag why dont we have div instead of ul

// opening div tag before the while loop


//and having a class of acf map just for css styling and jaascript for somethong to
hook into it

<div class="acf-map">
lets have a closing tag instead of closin unordered list ul tag

change it to closing div tag

save it

*****************Final code stage 4

<div class="acf-map">

<?php
while(have_posts()) {
the_post();
$mapLocation = get_field('map_location');
?>
<div class="marker" data-lat="<?php echo $mapLocation['lat'] ?>" data-lng="<?
php echo $mapLocation['lng']; ?>">

</div>
<?php } ?>
</div>

*********************************

we dont have a map because we didnt implement any Javascrit yet

but if we inspect element

we have wrapper div with a class of acf-map

if you inspect inside it

we see a div of each campus post

in this case each marker or pin


each have data attributes have the exact latitud and longitude value

Cool!
********************
Implement Tiny bit of javascript
USE ALL OF THAT DATA TO CONSTRUCT INTERACTIVE GOOGLE MAP

Luckily Google do Heavy Lifting For Us

Load in and Pull in javascript File


thats lives on the Google Servers they created

In wordpress if oyu to load javascriot file on the FrontEnd

yo want to got theme folders functions.php


go to line where you enque css and javascript file
so as we did before to load java script file
this time also we do it for goole map

thiis code will pull google map scripts from Google Servers
wp_enqueue_script hook

open parenthesis
lets begin with single quote within those
the first argument we want to make up the label of Scripts

lets say googleMap


next we want to point out to the interent pointing toward google map servers

here we dont https certain browser will throw error messages


for loading assets from secure connection

enclosed in the single quote within those


begin address with //
url to point google maps servers is s our url look like this

//maps.googleapis.com/maps/api/js?key=

afte key we past our API keys

othe argument will work just fine

NULL --meaning this script does depend on any other file

version number

true -- that we want to load this javascript file down toward the bottom of our
HTML page
instead ofuphead section

Complete Code in functions.ph add it after functions name

wp_enqueue_script('googleMap', '//maps.googleapis.com/maps/api/js?
key=AIzaSyBWkyG7p5jilXxbHXGD7GuOIdJzo8Czv-U', NULL, '1.0', true);

Lets Save that Refresh we still dont have a map


if we view the page source

scroll down to the bottom

you can see afew scripts Tag

here we see Google Maps URL


you click on it

succesfully open the tab with a bumch of new code thats means

we are in Business

COOL

MOve on to Next Step We Loded the JaVA sCRIPT thats live on the Google Servers

Now Just we need to write Javascript From Our End

to bascially Feed our Latitide and Longitude value


nto the Google Map Scripts

CODE
**********************

in a theme folder look into js folder insde this


sub folder modules create a javacscript named googlemap.js
and Add this code
rt $ from 'jquery';

class GMap {
constructor() {
var self = this;
$('.acf-map').each(function(){
self.new_map( $(this) );
});

} // end constructor

new_map( $el ) {

// var
var $markers = $el.find('.marker');

// vars
var args = {
zoom : 16,
center : new google.maps.LatLng(0, 0),
mapTypeId : google.maps.MapTypeId.ROADMAP
};

// create map
var map = new google.maps.Map( $el[0], args);

// add a markers reference


map.markers = [];

var that = this;

// add markers
$markers.each(function(){
that.add_marker( $(this), map );
});
// center map
this.center_map( map );

} // end new_map

add_marker( $marker, map ) {

// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'),
$marker.attr('data-lng') );

var marker = new google.maps.Marker({


position : latlng,
map : map
});

map.markers.push( marker );

// if marker contains HTML, add it to an infoWindow


if( $marker.html() )
{
// create info window
var infowindow = new google.maps.InfoWindow({
content : $marker.html()
});

// show info window when marker is clicked


google.maps.event.addListener(marker, 'click', function() {

infowindow.open( map, marker );

});
}

} // end add_marker

center_map( map ) {

// vars
var bounds = new google.maps.LatLngBounds();

// loop through all markers and create bounds


$.each( map.markers, function( i, marker ){

var latlng = new google.maps.LatLng( marker.position.lat(),


marker.position.lng() );

bounds.extend( latlng );

});

// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
map.setZoom( 16 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}

} // end center_map
}

export default GMap;

**********

you will chekc in a file that codes its going to find a div with a class of marker
that is for latitude and Longitude
// var
var $markers = $el.find('.marker');

f you are wondering where all the codes came from

or how i knew to write this code

if u go into the admion and check advnace Custom plugin

go to thie r documnetation

they had a page hoa to work with google map custom field
you will find a javascript code

https://www.advancedcustomfields.com/resources/google-map/

i pasted this file and converted it to Object Oriented

so we have google map script in a module folder

**************
now we need to jump into script file into js folder

thsi is our main file a kind of recipe file for our Jvascript

this file pull in all indivual ingredients


andmixes them all to gether one big bundled file

scriptsbundled.js to dialay on front en

so import or include googlemapjs file into this main file

add a new line import google map code

type import name it anyything you want here googlemap

quotes to get a gett a srting location


period slash to look into the curretn foilder
no need to write .js

semicolon at the end

and the path where the file resides

import GoogleMap from './modules/GoogleMap';

now we jut need to instatiat the true object using that class

var googleMap = new GoogleMap();

Save it

and rebundled or recomile this FIle

Step1
go to command line

navigating to local sites where webpack.config gulp file.js


drag this folders to the coomad line

then type gulp watch that will spin up the google proxy servers

nowq what ahappened anythin you will cahnged css and js file

its comand lin e tool watching and waiitng for u

if i hit save again comman automaticalyy rebundling that file

**********

step 2

maunally run gupl scripts

that recompile thing for us


go to front hard refresh
you will find interactive map with two pins east and west

visitor can zomm in and zom out

***********************************

Another task if user click the pin


seee the name of our campus

and even click the link to go to individual post


for that campus

then we also set up the template file for single campus

Cool
***********************************************************************************
***********

up in the header click campus


Campus Continued 3rd Video

in previous we create Google Interactive Map


where User can zoom around and scroll around

and we pinned our map location in our campus Post

with a post title displayed besides pin downtown west downtown east

right now if a user click a pin nothing happened

so our goal to set things up


if a user click a respective post pin
it will pops up a little bit of info the bane of a campus
may be a address

and if it click a post titlr just of a campus it will redirtect to a


peramalink detailed screen to a one indivdual campus post

so if we want to customize this screen


go to archivecampus.php in theme folder

we have while loop

thats output html once for each post

remeber that our javascript file code looking


here this javascript data attributes of
data latitude and data longitude
javascript code also look inide the div
the content we wnat to use for pop up

// so we output the title of the post and the street address


// create heading 3 level for the title of the Post

// drop in php

let call the the_title() wordpress function

to be orgainsied roght before the h3 tag drop and at the end of


after h3 tag

to do that lets go back into php

echo out the property that lives in our map location variable

$mapLocation this variable gives all the inforamtion located with the map
from this custom field map location

in square bracket as just as we used for lat and long here


we will use for address

Save

Cool

One step Further


make post title click linkable which
take you indivdual detail screen

lets create a tag and closin a tag to create a link


with href data attribute

isequal using
wordpress the_permalink function

now the title goes underline whihc soes it clinkable functionality


e are on apermalink

COOL!--

Code
<div class="acf-map">

<?php
while(have_posts()) {
the_post();
$mapLocation = get_field('map_location');
?>
<div class="marker" data-lat="<?php echo $mapLocation['lat'] ?>" data-lng="<?
php echo $mapLocation['lng']; ?>">

<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>


<?php echo $mapLocation['address']; ?>
</div>
<?php } ?>
</div>

***************************************
The onky issue is this post is desiged for BlogPost not Campuses
in order to get detailed view for campuses
we have to make a template file

CREATE A NEW FILE CALLED

single-campus.php

copy single-program file code into this file for a guid or a staritng place

CUSTOMIZING THE TEMPLATE for campus

change the Breadcrumb meta-info box


change to All Campuses instead of ALL PROGRAM

edit href change to campus


which we take it to campus archive
cool
remove the pagination link

pull a map for just a pin


inside generic content div
php the_content wordpress function

exclusing while loop code


delete while loop curly brackets

create map location variable with get_field value


remove the a tag no loger title to link unclick able
<?php
$mapLocation = get_field('map_location');
?>

<div class="acf-map">
<div class="marker" data-lat="<?php echo $mapLocation['lat'] ?>" data-
lng="<?php echo $mapLocation['lng']; ?>">
<h3><?php the_title(); ?></h3>
<?php echo $mapLocation['address']; ?>
</div>
</div>

now we have an individual screen for just one post or campus


if someone click on the screen it makes sense the user have some text content but
we no longer want to be a link
linking to a page somebody is lreadty on that page

remove the a tag jst wrapping the text

Perfect no title no longer have a link

Now we have custom indivdual screen for just campus post

*********************

ot would be very nice that we a section benath the content thats says

Program available at the this campus

in order to Create a REALTIONSHIP Between PROGRAM AND CAMPUS

we have to create a new custom Field

go to Admin

clcik on custom field

create a new group Related Campuses---1

add a new field Related Campuses----2

variable name get rid of parenthesis----3

just related_campus

Field Type instead of text lets related to Relationships---4 important!


Next field we need attention to Post type---5

limit just to campus post type

default option is ok

location box ----6


show this field group only post type only is ewual to program---7

publish this new field group

*******************
selct program go to edit math post
now we have campuses appear on the program edit post

select dowtown west


update

click campus link


now go to
downtow west to single view
front end campuses downtonwest

just write the php code to out put headlines that say
on individual campust post that says
Program available at this campus
then we create custom query to pull in any applicable program

cool
*********************************************

another Task

jump back into text ediotr here

single-campus.php

we have a modified map code


now because we create seingle campus file by duplicationg simple program.php file
code

you will noticed that in map code

we have few custom queries left over from the Program template
so we have related Professor Queires
below that ot checks that if it wmpty or not

modified code instead of professor to related program

<?php
$relatedPrograms = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'program',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'related_campus',
'compare' => 'LIKE',
'value' => '"' . get_the_ID() . '"'
)

if ($relatedPrograms->have_posts()) {
echo '<hr class="section-break">';
echo '<h2 class="headline headline--medium">Programs Available At This
Campus</h2>';
and then its output accordingly

we modify this custom Queries instead fo loking professor


it will look for related progrms

that wil saves us lot of typing

change varialble name to related porgram from professors

post page looks good

post type change it to program

order by and order look ok

but we have to Modify the meta query


so for the key instead of related program
change iot to related cmapus

Cool
so altogether we creting a new query

saying gives us any program post

where the related campus


contains the id Of a current campus we are viewing

now we have a CUstom Query

now jsut used in the code lets thats ouput stuff on that page

remeber we changed a variable with relsted profesor to related program


so update her also

dirsrt just asjust HEading level 2 we are just edchoingo out

only indeed ifa re realted program to show

here we jus say program available at this Campus

delete inide everything inside h2

in the while loops we dint want

inly having one string of HMTL

inside H2 Program available at this Campus

within the while loop we dont want


output a professord cards for each item

palin text link to a program

delete the li tag

a item its doens need aclass withe

We dont outout images


openin span elemt and Clocin span tag

Change the Professor class

min_lizt
gies th eapporpriate css styloing
now we ee in the individual campus program osy type

we have a text beeneth th e canpus Map


and if we click on it itakes me to the perfect screen

for program post

but we have to make reastionship flow in both directions


so may be at the bottom of the program page

we should have a section that says we have a program at this campuses

so to that set up

we have to go to single-program whcih is powerin this page

in a text editor
go to singleprogram.php

lets scrol down to very bottom

and at the while loops code

we are still in php

we have to write more of php

first thing first we do not need to write new custom query

remeber the Custom Field That creates the realtion ship

lives on the Program Post

we just look at the value

the custom field that associates with the Current Post


create a variable

*************

if ($relatedPrograms->have_posts()) {
echo '<hr class="section-break">';
echo '<h2 class="headline headline--medium">Programs Available At This
Campus</h2>';

echo '<ul class="min-list link-list">';


while($relatedPrograms->have_posts()) {
$relatedPrograms->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php }

***
echo '</ul>';
}

cool

*********************
garbage

You might also like