(Preamble: Am new to PHP, coming from a C# background where I am used to very clean code. Am currently working on my own Wordpress site which has a purchased theme.)
I have seen this type of code in a WordPress theme:
<img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo"/>
I find this very hard to read compared to the refactored:
<?php
echo '<a href="';
echo esc_url( home_url( '/' ) );
echo "><img src=";
echo esc_url( $logo );
echo " alt=";
echo esc_attr( get_bloginfo( 'name' ) );
echo '" id="logo"/></a>'
?>
But this is the easiest by far:
<?php
get_anchor($url, $imgsource, $alt, $id);
?>
get_anchor being a custom function that echos an anchor configured according to the parameters.
But surely I am not the first to think of this. Are there any existing libs that have a set of functions that return properly formatted html like in this example? Is there something I am missing?
I've written a function that returns a HTML tag based on the pure PHP output:
function tag($name, $attrs, $content) {
$res = '';
$res .= '<' . $name;
foreach($attrs as $key => $val)
$res .= ' ' . $key . '="' . $val . '"';
$res .= isset($content) ? '>' . $content . '</'.$name.'>' : ' />';
return $res;
}
$name is the tagname (e.g. a)
$attrs is a key, value array with attributes (e.g. array('href','http://google.com/'))
$content is the content / body of the tag (an other element or text)
Example basic use:
echo tag('a', array('href' => 'http://google.com/'),'Google');
Example nested use with multiple children:
echo tag('ul',array(),
tag('li',array(),'one') .
tag('li',array(),'two') .
tag('li',array(),'three')
);
I believe what you are looking for are templates like Smarty. They are the cleanest way to display information as code and view are completely separated.
However Wordpress do not use them, I don't know why actually, probably because most PHP programmers are not used to it.
Most of the PHP frameworks provide such libraries to out put html through parameterized functions, most of them are part of view layer if the framework follows MVC pattern.
but if you are not using any of the framework then you may use these libraries from here
PHP Pear Packages
And for building forms in particular see
HTML_QuickForm2
Related
I'm currently trying to keep to WordPress coding standards for an important exercise/job with an index page that loops through random posts, I'm using PHP Code Sniffer and getting this error:
Detected usage of a non-sanitized input variable: $_GET['my_posts_per_page']
Here is my code:
function my_random_posts() {
$my_posts_per_page = ! empty( wp_verify_nonce( $_GET['my_posts_per_page'] ) ) ? wp_verify_nonce( $_GET['my_posts_per_page'] ) : 10;
$randomised_posts = wp_get_random_posts( $number = $my_posts_per_page );
$output = '';
foreach ($randomised_posts as $randomised_post) {
$output .= '<li>';
$output .= '<h3>' . wptexturize( $randomised_post->post_title ) . '</h3>
<p>' . wptexturize( $randomised_post->post_content ) . '</p>
' . 'Read More' . '
</li>';
}
$output = '<ul class="randome_post">' . $output . '</ul>';
echo esc_html($output);
};
Also on the same line I'm getting this error:
Notice: Undefined index: my_posts_per_page
I've been scratching my head for hours here. Also, using the escape function on echo esc_html($output); now just brings all the code in (I know this is the purpose of the escaping function), though what's the point of this for Security when it shows the HTML without any embedded li, p, h3 tags, just the tag itself, for example:
<ul class="random_post"><li><h3>Hello world!</h3>
What do I do with the escaped HTML to get it to render correctly? And why am I getting an Undefined index?
For the actual post content, you might want to consider using WordPress function wp_kses_post( ), such as:
echo wp_kses_post( $content );
If it is just a small attribute for use within a tag, try using the WordPress function esc_attr( ), such as:
echo esc_attr( $attribute );
These will remove PHP code sniffer errors.
I have the following code which is inside its own file, which gets an ACF field and outputs it.
<?=get_field('text') ?>
I then include this in another template file using PHP include, meaning I have re-usable fields throughout my site. This has worked well in the past, as I can create consistent 'text' fields such as: <h1>My Text field</h1>
However, I'd like to further extend this by writing some kind of fucntion that allows me to call the PHP include, whilst also assigning the container tag (h1,h2 etc), as well as optional classes:
<h1>My Text field</h1>
<h2>My Text field</h2>
<p>My Text field</p>
<h1 class="myClass">My Text field</h1>
Is this possible?
You can do it this way:
<?php
class functions{
public static function get_field($text = 'Default', $tag = 'p', $class = false){
if($class){
$class = ' class="' . $class . '"';
}
return '<' . $tag . $class . '>' . $text . '</' . $tag . '>';
}
}
echo functions::get_field('My Text', 'h1', 'my-class');
?>
in HTML
<h1 class="my-class">My Text</h1>
Hope it will give you an idea on how to expand this method.
I was provided this bit of code to add to my functions.php file by the support team of the company from whom I bought the theme.
I wanted my logo and site name side by side and they gave me this code:
function igthemes_site_logo() {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
$url = home_url( '/' );
echo '<a href="' . esc_url( $url ) .'">';
echo "<img class='logo' src= " . $image[0] . " style='float:left; padding:15px;'>";
echo '<div style="float:left; padding:15px 0;">' . get_bloginfo( 'title' ) . '</div>';
echo '</a>';
}
However, that made it look like this.Two logos and titles
What do I change to just show one logo and one title?
it seems like that php function (igthemes_site_logo()) is called twice. That would be in the PHP code, not in the code you posted which only contains the function itself.
I created a bp-custom.php and regrouped the menu items fine. But now i am trying to add a link to go to /site/members. It list all the members.
When i add it though it goes under the profile I am viewing. I am redirecting to a wordpress page if that helps. Or is there a better way to do this.
Ex :
http://website.com/log-in/members/username/members/
I want it to go just here
http://website.com/log-in/members/
I would love to learn how to just put a url and no slug but whatever works. I do not know why it keeps referencing that signed in /member/username. I have even tried parent url and that did not work. I might have been using parent url syntax wrong.
Here is the function
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'Members',
'slug' => 'members',
'position' => 60,
)
);
}
I know that i can create .htaccess for this. But I don't want to do it.
May i know what is the clean way (alternate way) to do this?
I have tried what the user said in comment below and found in bp-members-template this function. I then added the part in bold to add the link but that did not work. I am just adding a google link for testing only.
function bp_get_displayed_user_nav() {
global $bp;
foreach ( (array) $bp->bp_nav as $user_nav_item ) {
if ( empty( $user_nav_item['show_for_displayed_user'] ) && !bp_is_my_profile() )
continue;
$selected = '';
if ( bp_is_current_component( $user_nav_item['slug'] ) ) {
$selected = ' class="current selected"';
}
if ( bp_loggedin_user_domain() ) {
$link = str_replace( bp_loggedin_user_domain(), bp_displayed_user_domain(), $user_nav_item['link'] );
} else {
$link = trailingslashit( bp_displayed_user_domain() . $user_nav_item['link'] );
}
echo apply_filters_ref_array( 'bp_get_displayed_user_nav_' . $user_nav_item['css_id'], array( '<li id="' . $user_nav_item['css_id'] . '-personal-li" ' . $selected . '><a id="user-' . $user_nav_item['css_id'] . '" href="' . $link . '">' . $user_nav_item['name'] . '</a></li>', &$user_nav_item ) );
**echo "<a href='http://www.google.com'>Google</a>"; }**
}
The bp_core_new_nav_item function is used to add a link to the user's navigation which explains why you're seeing URLs like /members/username/members/ when clicking on the tab. I don't think bp_core_new_nav_item is the right approach here.
An alternative approach would be to replace the function in your theme template that outputs the navigation with your own custom menu.
See this article on the BP Template Hierarchy which shows you how you can set up your own templates:
http://codex.buddypress.org/themes/theme-compatibility-1-7/template-hierarchy/
Sorry if this is a really stupid question. I am just starting to learn PHP and am probably jumping the gun a bit.
I am writing a very 'simple' wordpress plugin which has a custom post type and takes the content from it and returns it on the homepage with a shortcode. Below is the part of the code that handles the shortcode.
add_shortcode("new-tub", "new_tub_short");
function new_tub_short() {
$post_id = 87;
return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . get_post_field('post_content', $post_id) . '</a>';
}
So currently it wraps a link around the content of the post. All that is in the post will be an image, however, I would like to make it fool proof so it doesnt include another link and paragraph tag.
My question is, is it possible to search for the img tag within that post and return that only?
Thanks in advance,
Alex
You can do this by using strip_tags. Try this,
add_shortcode("new-tub", "new_tub_short");
function new_tub_short() {
$post_id = 87;
return '<a class="new-tub" href="' . home_url( '/test' , __FILE__ ) . '">' . strip_tags(get_post_field('post_content', $post_id), '<img>') . '</a>';
}
http://php.net/manual/en/function.strip-tags.php