target page with php based on page slug - php

Lets say I have six pages in wordpress
example.com/apples
example.com/art
example.com/bananas
example.com/broccoli
example.com/cars
example.com/cats
I want to target pages which slugs begin with specific letter
if (page slug beginns with "a"){
echo 'content for pages with slug beginning with a';
}
else if (page slug beginns with "b"){
echo 'content for pages with slug beginning with b';
}
else if (page slug beginns with "c"){
echo 'content for pages with slug beginning with c';
}
How do I write this correctly

Referring to this answer here, I'd say it's safe to get the URL like this:
/** Get the queried object and sanitize it */
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
/** Get the page slug */
$slug = $current_page->post_name;
And then:
/** Get the first character */
$slugBeginsWith = substr($slug, 0, 1);
/** Apply your logic */
if($slugBeginsWith == 'a')
{
echo 'content for pages with slug beginning with a';
}
elseif($slugBeginsWith == 'b')
{
echo 'content for pages with slug beginning with b';
}
elseif($slugBeginsWith == 'c')
{
echo 'content for pages with slug beginning with c';
}
However you didn't mention what is your goal here. Maybe if you provide more information in your question we could help better!

you need to get the firstcharacter by using php substr function. place following code in functions.php file
add_filter('the_content', 'change_content_by_firstCharacter');
function change_content_by_firstCharacter( $content ) {
global $post;
$post_slug = $post->post_name;
$firstCharacter = substr($post_slug, 0, 1);
if ( $firstCharacter == 'a' ) {
$content = 'content for a goes here';
} else {
return $content;
}
}

Related

WordPress functions.php custom code - I don't see error, but no render of content on frontend

I really need help with this code, because can't figure out why isn't working and even does not have syntax error, content is not rendered on frontend, at all.
I created quiz blocks with questions and answers. Now I want to show mixed types of ads after certain number of questions. Sample code below:
add_filter('render_block_buzzeditor/personality-question', 'add_question_ad_place', 10, 2);
add_filter('render_block_buzzeditor/trivia-question', 'add_question_ad_place', 10, 2);
global $question_count;
$question_count = 1;
function add_question_ad_place($block_content, $block)
{
// only after the 2nd question
if($question_count === 2) {
$block_content .= 'ad code after 2';
}
if($question_count === 4) {
$block_content .= 'ad code after 4';
}
if($question_count === 6) {
$block_content .= 'ad code after 6';
}
$question_count++;
return $block_content;
}​
Idea is to count question blocks, and after certain number of blocks (2,4,6 in this case) place ads code and have ad after 2nd, 4th and 6th question.
No PHP errors, but just does not render content on frontend. What am I missing here? Thanx, guys.
You are just incrementing $question_count in local scope, to fix add
global $question_count;
As the first line of your function add_question_ad_place
Like so
add_filter('render_block_buzzeditor/personality-question', 'add_question_ad_place', 10, 2);
add_filter('render_block_buzzeditor/trivia-question', 'add_question_ad_place', 10, 2);
$question_count = 1;
function add_question_ad_place($block_content, $block)
{
global $question_count;
// only after the 2nd question
if($question_count === 2) {
$block_content .= 'ad code after 2';
}
if($question_count === 4) {
$block_content .= 'ad code after 4';
}
if($question_count === 6) {
$block_content .= 'ad code after 6';
}
$question_count++;
return $block_content;
}​

Generate meta page title exactly as on h1 tag

Site based on Joomla. I have many pages where h1 header is mentioned as product detail and displayed based on product details through PHP. There are 2 files: default.php and view.html.php.
default.php :
<h1>Used <?php echo $this->CatName; ?> <?php echo $this->prodDet->prod_name;?> Toy for Sale </h1>
This correctly display the h1 tag. I want to generate meta title of the page and use this h1 output as generated in view.html.php. This line defines the title of the page :
$this->document->setTitle($title);
And this line defines header h1 :
"{$this->item->heading}";
Complete code :
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$title = null;
// Because the application sets a default page title,
// We need to get it from the menu item itself
$menu = $menus->getActive();
if ($menu)
{
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
}
else
{
$this->params->def('page_heading', JText::_('COM_USEDCAR_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$title = "{$this->item->heading}";
$this->document->setTitle($title);
if ($this->params->get('menu-meta_description'))
{
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->params->get('menu-meta_keywords'))
{
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
if ($this->params->get('robots'))
{
$this->document->setMetadata('robots', $this->params->get('robots'));
}
}
Output in title tag is heading. How to put this h1 tag output instead of $title?
Here's what the title portion of your code does:
// getting title from params
$title = $this->params->get('page_title', '');
// trying to get it right
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
// overwrite everything above with some value, making above code useless
$title = "{$this->item->heading}";
$this->document->setTitle($title);
I might be wrong but if I recall correctly, if a value doesn't exist it will return the variable name when cast into a string. Here "heading" might be empty.
You might want to change your code to something like this:
[...]
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
$this->document->setTitle($title);
You might as well like to save the title to session and reuse it everywhere:
[...]
$this->document->setTitle($title);
// save title to session
$_SESSION['page_title'] = $title;
and update the previous loop:
// getting title from params
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if (empty($title)){
[...]
Full code would be something like that:
[...]
session_id() || session_start();
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$_SESSION['page_title'] = $title;
$this->document->setTitle($title);
[...]
You might as well just ditch everything and go like that if you'd like:
[...]
$title = $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading) {
$title = $this->item->heading;
} elseif(
property_exists($this, 'CatName') &&
property_exists($this, 'prodDet') &&
property_exists($$this->prodDet, 'prod_name') &&
$this->CatName &&
$this->prodDet->prod_name
){
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
} else {
$title = $app->get('sitename');
}
}
$this->document->setTitle($title);
[...]
Code is untested but it should put you on the right track :)
Why don't you just send your h1 content to your php-document as GET parameter and then just output the it using echo inside the title tag? Unless you avoid dinamic echoing, this could be a fine solution for outputting text as title.
I would abstract away the logic of constructing the title/header to some function and then use this function to construct the title in both places.
function constructTitle($catName, $prodName) {
return "Used {$catName} {$prodName} Toy for Sale";
}
...
[in default.php]
<h1><?php echo constructTitle($this->CatName, $this->prodDet->prod_name); ?></h1>
[in view.html.php]
$this->document->setTitle(constructTitle(..., ...));
This allows you to have a single point to format your title while using it in several places.
The function needs to, obviously, be place in such position so that it can be accessed in both places and you need to have some way to get category name and product name in view.html.php. Im not familiar enough with joomla to know these things.
Edit:
To clarify, there is no real way to "extract" the title from the default.php as it is dynamic. You would need to process the php file then maybe you could do some regex magic, but this is in no way the proper solution to the problem.
you can just send your h1 content to your php-document as GET parameter and then output the it using echo in the title tag? Unless you avoid dynamic echoing,it would work.

How To Get Twig Template Engine Header Tags in PHP Function

I am trying to extend a Pico navigation plugin to exclude items from the navigation tree where the page's utilizes Twig template engine header tags.
My question is how do I get specific header tags from the .md files in the below PHP function and filter them to be excluded in the navigation tree?
The plugin currently implements the ability to omit items (pages and folders) from the tree with the following settings in a config.php file:
// Exclude pages and/or folders from navigation header
$config['navigation']['hide_page'] = array('a Title', 'another Title');
$config['navigation']['hide_folder'] = array('a folder', 'another folder');
The current function in the plugs' file uses the above config.php as follows:
private function at_exclude($page) {
$exclude = $this->settings['navigation'];
$url = substr($page['url'], strlen($this->settings['base_url'])+1);
$url = (substr($url, -1) == '/') ? $url : $url.'/';
foreach ($exclude['hide_page'] as $p) {
$p = (substr($p, -1*strlen('index')) == 'index') ? substr($p, 0, -1*strlen('index')) : $p;
$p = (substr($p, -1) == '/') ? $p : $p.'/';
if ($url == $p) {
return true;
}
}
foreach ($exclude['hide_folder'] as $f) {
$f = (substr($f, -1) == '/') ? $f : $f.'/';
$is_index = ($f == '' || $f == '/') ? true : false;
if (substr($url, 0, strlen($f)) == $f || $is_index) {
return true;
}
}
return false;
}
I need to add the ability of omitting items (or pages) from the tree using the Twig header tags 'Type' and 'Status' like so in the .md files:
/*
Title: Post01 In Cat01
Description: This post01 in cat01
Date: 2013-10-28
Category:
Type: post // Options: page, post, event, hidden
Status: draft // Options: published, draft, review
Author: Me
Template:
*/
...
The MarkDown content . . .
So if a user wants to remove items tagged with "post" in the 'type' tag and/or "draft" from the 'draft' tag (see header above), they would then add the linked tags in the array below that I added into the config.php:
// Exclude taged items:
$config['navigation']['hide_status'] = array('draft', 'maybe some other status tag');
$config['navigation']['hide_type'] = array('post', 'etc');
I also added the following to the bottom of the at_exclude() function:
private function at_exclude($page) {
. . .
foreach ($exclude['hide_staus'] as $s) {
$s = $headers['status'];
if ($s == 'draft' || 'review') {
return true;
}
}
foreach ($exclude['hide_type'] as $t) {
$t = $headers['type'];
if ($t == 'post' || 'hidden') {
return true;
}
return true;
}
. . .
This is obviously not working for me (because my PHP knowledge is limited). Any help with what I am missing, doing wrong or how I can add this functionality will be greatly appreciated.
I dived into the (not so beautiful) Pico code and those are my findings.
First of all, Pico doesn't read every custom field you add to the content header.
Instead, it has an internal array of fields to parse. Luckily, an hook called before_read_file_meta is provided to modify the array.
In at_navigation.php we'll add:
/**
* Hook to add custom file meta to the array of fields that Pico will read
*/
public function before_read_file_meta(&$headers)
{
$headers['status'] = 'Status';
$headers['type'] = 'Type';
}
This will result in Pico reading the headers, but it won't add the fields to the page data yet. We need another hook, get_page_data. In the same file:
/**
* Hook to add the custom fields to the page data
*/
public function get_page_data(&$data, $page_meta)
{
$data['status'] = isset($page_meta['status']) ? $page_meta['status'] : '';
$data['type'] = isset($page_meta['type']) ? $page_meta['type'] : '';
}
Now, in the at_exclude function, we can add the new logic.
(Instead of cycling, We configure an array of status and types we want to exclude, and we'll check if there is a match with the current page status/type)
private function at_exclude($page)
{
[...]
if(in_array($page['status'], $exclude['status']))
{
return true;
}
if(in_array($page['type'], $exclude['type']))
{
return true;
};
return false;
}
Now let's customize our config.php (I standardized the configuration with the plugin standards):
$config['at_navigation']['exclude']['status'] = array('draft', 'review');
$config['at_navigation']['exclude']['type'] = array('post');
All done!
But if you are just starting out, I'd advise you to use a more mature and recent flat file cms. Unless you are stuck with PHP5.3
I decided to simplify the function to omit it from the config.php since it really isn't needed to be set by the end-user. By doing so, the at_exclude() function is much simpler and quicker on the back-end by omitting all the checks via other files:
at_exclude {
. . .
$pt = $page['type'];
$ps = $page['status'];
$home = ($pt == "home");
$post = ($pt == "post");
$event = ($pt == "event");
$hide = ($pt == "hide");
$draft = ($ps == "draft");
$review = ($ps == "review");
$type = $home || $post || $event || $hide;
$status = $draft || $review;
if ( $type || $status ) {
return true;
};
return false;
}
Obviously it needs some tidying up but you get the picture. Thnx

How To Overwrite Meta Tags?

I have index.php page with "default" meta tags, with switch function I call e.g. single_page.php and its looks something like www.something.com/?page=single_page.
how can I overwrite meta tags from index page with meta tags from single_page.php
$conlibrary="play/pages/" ;
IF(!isset($_GET['page'])){
$page = 'deafault';
} ELSE {
$page = $_GET['page'];
$findme = '&';
$pos = strpos($page, $findme);
IF ($pos ===true) {
$data = explode("&", $data);
$dest =$conlibrary."/".$data[0].".php";
IF (file_exists($dest)) {
$page = $_GET['page'];
} ELSE {
$page = '404';
}
} ELSE {
$dest =$conlibrary."/".$page.".php";
IF (file_exists($dest)) {
$page = $_GET['page'];
} ELSE {
$page = '404';
}
}
}
include($conlibrary . $page .".php");
If you really need to modify meta tags, and depending on the specific situation, my strategy would be to give the meta tags ID attributes and then make the alterations using Javascript, as in this gist.
It doesn't work so well if the alterations need to be made before the page is sent to the browser; as PHP is not a primary language, my amateur instinct would be to simply use string variables for the "default" meta tags (rewriting the code if required) so that the included file could modify those strings as necessary.

How do you maintain page number after redirect in CakePHP?

I have an index view that lists items, and it's a long list so I use Paginator to limit items to 50-to-a-view.
Each item has an "edit" link that goes to an edit view with inputs/validations/etc. When that form is submitted, I redirect the use back to the index view.
So far so good, but here's the rub:
If a user is on page N of the index and they click edit and edit an item, I want them to be redirected back to page N of the index. If I knew the page number, I could just stick "/page:N" on to end of the URL, but I have no idea how I can get the page number. (N could be any page number, but especially >=2)
Any ideas would be appreciated.
The page number should be part of the $params var in the list view. Just tack it onto the end of the edit link and handle it from there. On the edit page you will need a way to take in the optional page number, store it during any form submission, and forward back to the list with the same page number.
I created a component that saves the page in the session. Then in the app_controller.php, I check to see if there is anything in the session for the particular model being used and then add that to the url. If you are interested in the code for the component, message me. I also store the order, if the user changed the sort order in the index page before editing.
See here for the source:
http://github.com/jimiyash/cake-pluggables/blob/a0c3774982c19d02cfdd19a2977eabe046a4b294/controllers/components/memory.php
Here is the gist of what I am doing.
//controller or component code
if(!empty($params['named']) && !empty($params['controller']) && $params['action'] == 'admin_index'){
$this->Session->write("Pagem.{$params['controller']}", $params['named']);
}
//app_controller.php
$redirectNew = "";
if(is_array($redirectTo)){
if(!empty($params['prefix']) && $params['prefix'] == 'admin'){
$redirectNew .= '/admin';
}
if(!empty($params['controller'])){
$redirectNew .= "/" . $params['controller'];
}
if(!empty($redirectTo['action'])){
$redirectNew .= "/" . $redirectTo['action'];
}
} else {
$redirectNew = $redirectTo;
}
$controller = $params['controller'];
if($this->Session->check("Pagem.$controller")){
$settings = $this->Session->read("Pagem.$controller");
$append = array();
foreach($settings as $key=>$value){
$append[] = "$key:$value";
}
return $redirectNew . "/" . join("/", $append);
} else {
return $redirectNew;
}
If I understand correctly, the above is fine for editing, but not for adding. This solution should work for both situations:
In your controllers or your /app/app_controller.php, put in something like this for adding:
$insertID = $this->{$this->modelClass}->getLastInsertID();
$page = $this->{$this->modelClass}->getPageNumber($insertID, $this->paginate['limit']);
$this->redirect("/admin/{$controllerName}/index/page:{$page}");
...and something like this for editing:
$page = $this->{$this->modelClass}->getPageNumber($id, $this->paginate['limit']);
$this->redirect("/admin/{$controllerName}/index/page:{$page}");
In your /app/app_model.php, put in this:
/**
* Work out which page a record is on, so the user can be redirected to
* the correct page. (Not necessarily the page she came from, as this
* could be a new record.)
*/
function getPageNumber($id, $rowsPerPage) {
$result = $this->find('list'); // id => name
$resultIDs = array_keys($result); // position - 1 => id
$resultPositions = array_flip($resultIDs); // id => position - 1
$position = $resultPositions[$id] + 1; // Find the row number of the record
$page = ceil($position / $rowsPerPage); // Find the page of that row number
return $page;
}
Hope that helps!
Does a simple
$this->redirect($this->referer());
works?
In view with paginator:
<?php
if ($this->Paginator->hasPage(null, 2)) {
$pag_Start = $this->Paginator->counter('{:start}');
$pag_End = $this->Paginator->counter('{:end}');
if( $pag_Start == $pag_End ){
$pageToRedirect = $this->Paginator->current('Posts');
}else{
$pageToRedirect= '';
}}?>
Then link to edit page
<?php
echo $this->Form->postLink(
'Edit',
array('action' => 'edit', $subscription['Post']['id']));
?>
In controller:
public function edit($post_id, $pageToRedirect = false){
//after all editing its done redirect
if($pageToRedirect){
// if record was last in pagination page redirect to previous page
$pageToRedirect = $pageToRedirect -1;
return $this->redirect(array('action' => 'index/page:'.$pageToRedirect ));
}else{
// else redirect to the same pagination page
$this->redirect($this->referer());
}
}

Categories