INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to add an option to admin to add image that could be used as header?
I want to add an option to add/change an Image in admin dashboard in a way that I can call it through code. For example lets call it header_2 Image and then want to use it in an header template. So that users later on can change this image without editing header template. | This is how I did it in the end. I installed Types plugin and created a custom post type with only featured Image and title.
I created one post of this type.
Removed GUI to add more posts of this type.
Using another plugin Admin Menu Editor I added menu Item to edit the only post of this custom type. Now this Image can be changed at any time.
and I displayed featured Image of this post in the page I had to. Once this post is changed. It changes in the page as well.
More like a tweak but for user it is very easy to use and works as required. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, customization, themes"
} |
SQL Query to Get list of all users along with their blogs
How to query for a list of users along with the blogs in which they are member of in a multi site wordpress installation.
For example, I need the results as below
user domain
abc xyz.com
abc example.com
ggh example.com
I tried the below query, but its not listing all the domains..
SELECT DISTINCT a.user_login, a.user_email, c.domain
FROM wp_users a
JOIN wp_usermeta b ON a.id = b.user_id
JOIN wp_blogs c ON b.meta_value = c.site_id
LIMIT 0 , 100
I am not sure how the network/multi site works.. can anyone please tell me how to get the result? | You can use `get_blogs_of_user()` to get all the blogs of a given user.
So to get a list sorted by the users:
global $wpdb;
$blogs = array();
$user_ids = $wpdb->get_col( 'SELECT ID FROM $wpdb->users' );
foreach( $user_ids as $user_id ) {
$blogs[$user_id] = get_blogs_of_user( $user_id );
}
// you can use var_dump( $blogs ); to see what's in the $blogs array | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "multisite, mysql"
} |
Same template for all the terms of a taxonomy
My problem is the following.
I have a custom post type called "photography" which contains a taxonomy called "photographyCategories", which contains several terms : "outside", "inside", "portrait"...
All these terms content is based on the same outline (a list of pictures and a slider).
I know that if I want to display the archive page of one of these terms I have to create, for example, the file taxonomy-photographyCategories-outside.php. I've done it and it works.
But what I want is ONE template for all these terms. I don't wanna have an "outside" template, an "inside" template and a "portrait" template because they're all the same... They display the same type of content, except the photographies that are different.
I can't find a way to do this...
Is there a solution ? | According to template hierarchy you have to create the template
taxonomy-photographyCategories.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, taxonomy, archives"
} |
List of default WordPress URLs
I'm looking for a list of all possible URLs (or URL patterns) that would deliver content or would otherwise cause WordPress to respond to the request with something other than a 404. Let's assume a fresh standard install of the current version.
I've looked around and there's lots of documentation on how to create custom URLs to your content or admin area or for various other things, but I haven't found a comprehensive list of what exists by default. Does such a list exist or is there an easy way to compile it? | Currently I can't offer a full answer to your question, but here as a starting point a (PHP 5.3+/closure) plugin that dumps the global `WP_Rewrite` object into the `shutdown` hook.
<?php
/* Plugin Name: Show WP_Rewrite Dump at the last hook (shutdown) */
add_action( 'shutdown', function() {
var_dump( $GLOBALS['wp_rewrite'] );
} );
This doesn't take redirects into account. If someone would for e.g. write
exit( wp_redirect( home_url() ) );
somewhere, you wouldn't know that inside `WP_Rewrite`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "urls"
} |
How to hook wp_mail to add a custom email as BCC for each sent email?
Is there a way to hook into the wp_mail function to add a custom email as hidden (BCC) copy to each email sent?
If so, how?
-edit-
It's not like I want to send an email with BCC, I would like to make the necessary hooks to add the BCC to every sent email (many different functions in my theme make use of `wp_mail`) | You have multiple options:
1. The function is pluggable (i.e., you could write up your own `wp_mail` function and make it do what you'd like).
2. There's the `phpmailer_init` hook, which gives you access to the `$phpmailer` object (and thus lets you `AddBcc` another email address.
3. There's the `wp_mail` hook, which gives you (amongst other things) access to `$headers`, where you could add another email address to the `'bcc'` field. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "functions, hooks, email"
} |
Plugin can't write to database even though permissions appear correct?
I'm using the Formidable Form plugin, and when I try to add a form, the form isn't saved. According to the developer, the user does not have sufficient permissions to write to the database. Here's how my wp-config.php looks:
define('DB_NAME', 'wordpress_clouse');
/** MySQL database username */
define('DB_USER', 'wordpress_user');
/** MySQL database password */
define('DB_PASSWORD', 'mypass');
/** MySQL hostname */
define('DB_HOST', 'localhost');
wordpress_user has 'All Privileges' under phpMyAdmin, so I don't see where the discrepancy is. Why would the plugin be unable to write to the database if permissions appear in order? | The Formidable Form plugin seems to ignore database errors in many places in the code. Setting `WP_DEBUG` to true uncovered that the forms are not created because some tables are missing (no indication is given to the user).
Further investigation has shown that the tables fail to create when the plugin is activated (no indication is given to the user).
The underlying root cause that leads to table creation failure is that some of the tables are using nullable fields in unique keys, which is currently not supported by the Cloud Storage Engine (ClouSE). So the solution here is to alter the creation statement to make the fields that are used in unique keys not nullable. The patch is provided via OblakSoft support channels. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, permissions, phpmyadmin"
} |
functions.php return custom text
I am looking to add custom text to the site in functions.php.
I am using multisite. Is there a hook to determine which site so I can alter the text?
For example:
function greeting(){
if(site_name('one'){
echo 'hello';
} elseif(site_name('two')){
echo 'goodbye';
}
} | You can use **`get_blog_details()`** to do it.
Use it the following way:--
function greeting() {
global $blog_id;
$current_blog = get_blog_details( $blog_id );
if ( 'one' == $current_blog->blogname ) {
echo 'hello';
} elseif ( 'two' == $current_blog->blogname ) {
echo 'goodbye';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, multisite"
} |
how to add limit records in wordpress query
I have this query which is returning the all records from database whose type is equal to 'quote2'. No I want to know how to limit the record. I mean I just want to show last 10 records added in the database. I am new in wordpress and want to learn syntax of my required query.
global $wpdb;
$querystr = "select $wpdb->posts.*
FROM $wpdb->posts
WHERE $wpdb->posts.post_type = 'quote2'
"; | What you want to do, can be achieved by means of the `WP_Query` class.
$query = new WP_Query(array(
'post_type' => 'quote2',
'posts_per_page' => 10, // or something else
));
Now you can work with `$query` like:
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post;
?>
<h1><?php the_title(); </h1>
<?php the_content();
<?php
}
else {
// No posts...
}
If you just want to get access to the posts, you can do so via `$query->posts`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "wp query, database"
} |
Page not found error when adding text `2 = 2 ^ 1` to the page
Adding the following text to a page in the Text editor and clicking `Update` results in "Error 404 - Page Not Found":
2 = 2^1
Replacing this text with anything else makes the Update succeed.
Any ideas what might be causing the error?
**Update:**
After some experimentation I've discovered a more general form of input leading to errors:
<number> = <number> ^
with the same number on both sides of the equal sign.
For example, `100 = 100 ^` gives an error while `100 = 101 ^` doesn't. | This is an issue when installing mod_security2.
The solution is as simple as disabling mod_security or allowing that page to POST that request.
The issue is that mod_security thinks someone is trying to hack into your site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages, errors, 404 error"
} |
remove all custom post created
i will automatically create a lot of post with the wp_insert_post function
<?php wp_insert_post( $post, $wp_error ); ?>
all those custom post type will be call "house" and then after some testing, i what all those post and the revision to be deleted, to clear and clean the DB... so how i do that ?
i do all my request with $wpdb what is the query to delete/remove all post_type = house and there revision ? | Manipulating posts directly in database is rarely good idea, since it skips all the APIs, hooks and so on that normally participate in the process.
You should use `get_posts()` to retrieve the list and `wp_delete_post()` for deletion to ensure it is done properly and there are no leftovers. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, wpdb"
} |
Separate [Advanced Custom Field] values by commas
I have a 'relationship' custom field that allows you to select multiple values and display them via
<?php $post_objects = get_field('field');
if($post_objects!=''){ ?>
<?php foreach( $post_objects as $post): ?>
<?php setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>,
</a>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
This works for now but is not very pretty as it returns the values as "Value, Value, Value,". What I would like it to output is...
> 1 Value = "Value"
>
> 2 Values = "Value & Value"
>
> 3 or more Values = "Value, Value & Value"
" | Try to grab the output and echo together.
<?php $post_objects = get_field('field');
if($post_objects!='') :
$value = array(); ?>
<?php foreach( $post_objects as $post): ?>
<?php setup_postdata($post); ?>
<?php $values[] = '<a href="'. get_permalink() .'">'. the_title('','',false) .'</a>'; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php echo join( ', ', $values); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields"
} |
Comparing Dates from custom field
I am trying to compare dates from a custom field. I have them stored as something like "20121125". If the date has expired, a placeholder image will be used, if not, the default thumbnail will be used. Any advice is appreciated.
<?php
$html = "";
$key = get_post_meta($post->ID, 'Due', true);
$date = date('ymd');
if ($key >= $date) {
the_post_thumbnail('medium');
} else {
$html .= '<img src=" alt="">';
}
return $html;
?> | Well, the exact server time/timestamp can be retrieve with current_time function. And comparing your date format, it would need to be Ymd. So combining these two thing, the proper comparison for you should be -
$key = get_post_meta( $post->ID, 'Due', true );
$date = date('Ymd', current_time('timestamp') );
if( $key >= $date )
{
// note to retrive the post thumbnail, you need to use get_the_post_thumbnail,
// as the_post_thumbnail function actually echo the output
$html .= get_the_post_thumbnail(null, 'medium');
}
else
{
$html .= '<img src=" alt="">';
}
return $html;
Now, there could be one question in which timezone you are saving the date in the post meta. If the value is sanitized with the server time (as the post_date value is saved), then this is perfect comparison. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, custom field, date time"
} |
How to load wordpress environment without loading the template?
Basically I want to use wordpress functions for example `wp_create_user()` or `wp_update_user()` outside of wordpress (outside of wordpress directory).
I tried with all the below code snippets to load the wordpress environment, I am able to use the functions correctly in both the cases but the problem is that this also loads the wordpress template which I do not want.
**First Method:**
<?php
define('WP_USE_THEMES', false);
require ('../blog/wp-load.php');
?>
**Second Method:**
<?php
define('WP_USE_THEMES', false);
require ('../blog/wp-blog-header.php');
?>
**Directory Structure:**
/blog
|
|_ Wordpress installed here
/admin
|
|_ admin.php (I want to use wp functions here)
Note: I am using **Writr theme** in my wordpress blog. | Well I don't know the reason how this worked but it did.
At first, I was loading the wp environment in the beginning of my file and it was loading the wp template(wp theme) which I didn't want.
But now I loaded the wp environment at the end of the file and it worked. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp load.php, wp blog header.php, outside wordpress"
} |
wp-pagenavi getting 404 page not found
Wordpress WP-PageNavi plugin gettinf 404 error. here is my code.
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array(
'posts_per_page' => 3,
'paged' => $paged
)
); ?>
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title('<h1 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute('echo=0') . '" rel="bookmark">', '</a></h1>'); ?>
<?php endwhile; if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
<?php wp_reset_query(); else : ?>
<p class="no-posts"><?php _e('Sorry, no posts matched your criteria', 'example'); </p>
<? php endif; ?> | Maybe you missed the object here, and by the way why do you use query_posts() ? You can try this :
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 3,
'paged' => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title('<h1 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute('echo=0') . '" rel="bookmark">', '</a></h1>'); ?>
<?php endwhile; if(function_exists('wp_pagenavi')) { wp_pagenavi($query); } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, plugin development"
} |
Using composer for dependency management in plugindevelopment
I'm new to wordpress plugin development. Normally I would use composer to add thirdparty libs to my code, but I couldn't find any wordpress plugin on github that uses composer for that.
I read about wpackagist.org and the way composer can be used to manage dependencies between wordpress plugins. In this case there would be one master composer.json with all infos.
But what if I want to develop a single plugin using composer? Would I simply include the autoload in the "plugin root"-file? But what if other plugins would do it the same way and would bring own autloaders and in the worst case have the same dependencies in different versions?
Is there a best practice for integrating lib-dependencies into wordpress plugins? | There are still very few WP plugins/themes that are being developed Composer-first. You can take a look at Laps case study (one of mine) for practical example.
Essentially if you plan for plugin to be publicly distributed you need to take care of both cases - running it as part of whole-site Composer stack and running it standalone.
In practice this usually means looking and conditionally loading autoloader if its present (with rest of vendor stuff) inside plugin's directory. Along the lines of:
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) )
require __DIR__ . '/vendor/autoload.php';
This doesn't address issue of multiple plugin with duplicated dependencies, however it's _no worse_ than exactly same thing happening without Composer involved. Simply put WordPress has no native dependency management, so the only way to reliably handle it is introduce it externally - such as managing whole WordPress stack with Composer. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "plugin development, composer"
} |
Directory location of new page
I see from the WordPress dashboard, I can create many new pages. When I create a new page, can you please tell me where this new page will be created. I mean the `directory location` where this file will be created? | WordPress does not create a new file in the filesystem when you create a page from the backend. The data you enter into the backend is saved to the MySQL database where it is retrieved by various and sundry queries and displayed by code in one or more templates. There is no "directory location" for your individual pages, but the template files that control the page display can be found in `wp-content/themes/your-theme-name/` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, directory"
} |
WP not recognizing custom post type / template
I've created a custom post type:
$args = array(
'labels' => array(
'name' => __( 'Prosjekter' ),
'singular_name' => __( 'Prosjekt' ),
'add_new' => __('Nytt prosjekt')
),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'has_archive' => false,
'taxonomies' => array('category'),
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'page-attributes','post_tag' ),
'rewrite' => array('slug' => 'prosjekter')
);
register_post_type( 'project',$args);
Then I've created this template file:
single-project.php
But when I open a project it's not using the template. What am I missing? | Change public to true. Else if not to be public then I'm not sure you can use or need a template. If you do need some sort of interface for administrators that works via theme. Then I think you need to set public to true and use other values to prevent public querying etc
See Wordpress.org < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, templates"
} |
Assign single template to multiple custom post types?
I have a number of custom post types that I would like to display with the same template which I have created initially as `single-photography.php` in my theme.
Is there any way to assign this template to multiple custom post types?
I understand I can probably do this within the `single.php` file with a conditional include based on `get_post_type()`, but I'm wondering if there is a better way? | You can filter `template_include` and pass your custom template as return value depending on your own conditions.
Sample code, not tested:
add_filter( 'template_include', function( $template )
{
// your custom post types
$my_types = array( 'photography', 'painting' );
$post_type = get_post_type();
if ( ! in_array( $post_type, $my_types ) )
return $template;
return get_stylesheet_directory() . '/single-photography.php';
}); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "custom post types, theme development, templates"
} |
Send button using own contact form
I have an own contact template here , und built it according to this info.
The submit button does not work because another event seems to block the reload of page. Looking in the console, I see an xml http post request which I do not want. Can you help to find the js code that blocks the reload. Should I post the header.php or the page-contact-us.php? Contact form 7 is installed, do I have to drop the plugin?
I used contact form 7, but would like to change the required property of a field dynamically: if the checkbox is clicked, the address fields should change from non-required to required. This can be done with php, but I dont know how to change the php code of cf7 | If you don't need to use Contact Form 7 (as you are creating your own custom contact form), deactivate the plugin to solve the conflict. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "ajax, plugin contact form 7, contact"
} |
How to return value from sql and display it
In ordinary php I don't have that kind of problem I think but in WP this is a different story. I have query and I want return one value from "liczba_wodo" column.
global $wpdb;
if (isset($_POST['submit'])){
$spr_liczbe_wodo = $wpdb->get_row ("select liczba_wodo from wp_ow_adres where adres='Street 12/6'");
foreach ( $spr_liczbe_wodo as $print ) {
echo $print->liczba_wodo;
echo 'Echo test';
}
}
}
Of course 'echo test' works fine. I think that "$spr_liczbe_wodo" is null or something. Thanks for help. | If you need to return one _value_ then use `get_var` instead of `get_row`. `get_var` will return a string. `get_row` will return an array or object.
$spr_liczbe_wodo = $wpdb->get_var ("select liczba_wodo from wp_ow_adres where adres='Street 12/6'");
var_dump($spr_liczbe_wodo);
The problem with your code, by the way, is that `$spr_liczbe_wodo` is an object, but when you loop over it `$print` is not but you attempt to use it as if it were an object anyway. Through in a couple of `var_dump`s and you can easily see the problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, sql"
} |
Filter / add_action to upgrade.php page
I'm wanting to change the wording and add some styling to the upgrade.php page.
We have a situation where we update our codebase across multiple sites via Git - when a user logs in after the update they are greeted with the "You must update your database" message.
This is fine but we want to refine the page a little, either filtering the text or adding a script to do it the dirty way.
The problem is I don't see any hook for this page and the text is hardcoded in upgrade.php.
Any help appreciated :) | Well, the first lines of that file, not counting comments/headers, are...
/** Include user install customize script. */
if ( file_exists(WP_CONTENT_DIR . '/install.php') )
require (WP_CONTENT_DIR . '/install.php');
You could include a custom install script with the rest of your code. That seems the most straightforward approach to me. It is hard to say a lot more as you haven't said what you want to do in much detail. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, wp admin, upgrade"
} |
Get current active wp color scheme
Is there a way to return the current active color scheme?
This is how to register a new admin color scheme
<?php register_admin_color_schemes(); ?>
is there something like `get_admin_color_scheme();` that will return which is active? | The current admin color scheme is a user setting, you can get its value with:
$current_color = get_user_option( 'admin_color' );
See the function `admin_color_scheme_picker()` in `wp-admin/includes/misc.php` for an usage example. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "admin"
} |
Privilege to recover trashed posts
I can't seem to find which built in privilege is required for recovering a trashed post. Would it be `delete_posts`, which is as its name suggests, can move items into the trash and remove them completely, or `edit_posts` or `publish_posts`..?
I aim to have something like, when an admin trashes a post of a lesser role, that lesser role should not be able to recover it. I don't want to add a new capability. | The capability is `delete_post`, you can see it in source here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, capabilities, customization"
} |
how to add home icon instead of text in wordpress menu
i need to add "home.png" icon image as home button instead of text for example !enter image description here
i searched this question in google and find out a way, but that didn't work. the method mentioned in those sites are
1. enable css class in screen options in apperance>>menu
2. write a class "home-icon"
3. in style.css insert this class. i wrote the code as
.home-icon{ background-image:url(images/home.png); }
i followed this site but this didn't work for me. what is the problem in this method? or any other alternative ideas? | i solved the problem by using a plugin named nav-menu images | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, homepage, icon"
} |
How to fix empty dashboard issue in WordPress?
A site of my company uses blog on WordPress 3.3.1 with theme based on Twenty Ten. Last week I upgraded Apache and PHP on our production server. Afterwards the dashboard refused to work. When a user logs in, a blank dashboard appears. A menu with links is still present, but none of the links work, so one cannot create new posts etc. In the page source I see the following message:
> **Fatal error** : Access to undeclared static property: WP_Screen::$this in **blog/wp-admin/includes/screen.php** on line **706**
There were no changes to WordPress configuration made and no new plugins installed. How to fix the issue? | There is a bug in WordPress 3.3.1 causing the issue. It may affect other versions as well.
To solve the issue you can update WordPress to the current stable release and do integration testing afterwards. Or you can do a quick bug fix.
To fix the bug:
1. Open file **blog/wp-admin/includes/screen.php** in your favorite text editor.
2. On line **706** find the following PHP statement: `<?php echo self::$this->_help_sidebar; ?>`
3. Replace it with the statement: `<?php echo $this->_help_sidebar; ?>`
4. Save your changes.
Hope it helps you. | stackexchange-wordpress | {
"answer_score": 83,
"question_score": 43,
"tags": "fatal error"
} |
pre_get_posts action doesn't work
I'm trying to load only two types of posts ( 'news' and 'reviews' ) in `home page` using `pre_get_posts`:
// Load Home Page Posts( reviews and news )
function search_home_posts( $query ) {
if( $query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set( 'post_type', array( 'reviews', 'news' ) );
}
}
add_action( 'pre_get_posts', 'search_home_posts' );
But it doesn't seem to do nothing, since all post types and pages are shown in the `home page`. Any idea of what is happening? | There is nothing wrong with that code. It's correct and working fine for me on a default installation.
Change to using the default theme. Does it work now? If so, then there's something wrong with your theme.
Disable other irrelevant plugins. Does it work now? If so, then one of those plugins was interfering.
Eliminate the possible conflicts until the code works the way you expect it to work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, pre get posts"
} |
Add a custom text to admin footer in a Custom Post Type page
I want to customize the footer text in a Custom Post Type admin page. I have a plugin that creates this custom post type and want to add in it a function to customize admin_footer_text.
As you can see in code below I can change the footer text, but only globaly.
function my_custom_footer_admin_text () {
echo 'my custom message,';
}
add_filter('admin_footer_text', 'my_custom_footer_admin_text');
Does someone knows the hook of a custom post type page? Or how can I change the footer text of a certain Custom Post Type page? | This should do. Put the following in your `functions.php`
if (in_array($GLOBALS['pagenow'], array('edit.php', 'post.php', 'post-new.php')))
add_filter('admin_footer_text', 'my_custom_footer_admin_text');
function my_custom_footer_admin_text($text) {
$post_type = filter_input(INPUT_GET, 'post_type');
if (! $post_type)
$post_type = get_post_type(filter_input(INPUT_GET, 'post'));
if ('my_post_type' == $post_type)
return 'my custom message';
return $text;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types, wp admin, hooks"
} |
How to display date of blog creation
Is it possible to display (in PHP) the year when the blog was created? I want use this in footer (copyright) on my several blogs with my theme. | Actually it is possible if the first user account exists (with user id 1). Then you can use -
<?php echo mysql2date('Y', get_user_option('user_registered', 1) ); ?>
The concept behind this is, when a WordPress Blog Installed, one user account created, and we are using his/her registration time. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, date"
} |
Change header when on home page
Im trying to make my home page have one type of header which is different from every other page. I have made a page the front page in the settings called home and in header.php i have changed the code to this:
<?php if(is_home()) {?>
<hgroup>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><img src="<?php echo "Hello World" ?>"/></a></h1>
</hgroup>
<?php } else {?>
<hgroup>
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><img src="<?php bloginfo('template_url'); ?>/images/Cranbri-web-solutions.png"/></a></h1>
</hgroup>
<?php } ?>
Can anyone see whats wrong? because for some reason the header inst changing??
Thanks | Since you have a static page as the front page, use `is_front_page()` instead of `is_home()` in the condition. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "homepage, headers"
} |
What are trackbacks?
I was wondering what are trackbacks. I found this to be an option in Wordpress, and I am wondering if I should add them to pages and posts. Thank you for your help and support! | Trackbacks (and their close relatives pingbacks) are rather well documented in Codex under Managing Comments. Essentially it's a form of automated comment which other sites can use to notify they have something relevant to specific post.
Note that just as normal comments these are very heavily spammed and some form of antispam is a must. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages"
} |
BackupBuddy WP CLI Invalid Profile Error
When I try to run a WordPress (3.8) backup of a site using wp-cli 10 alpha (site here)
wp --info
PHP binary: /usr/local/bin/php-5.3
PHP version: 5.3.5
php.ini used: /etc/php53/php.ini
wp-cli root: /usr/local/wp/vendor/wp-cli/wp-cli/php/
wp-cli config:
wp-cli version: 0.10.0-alpha
on my Dreamhost VPS in combination with BackupBuddy 4.2.12.1 I get this error
wp backupbuddy backup profile-name
Error: Error #85489548955. Invalid profile ID not numeric: `profile-name`.
Any ideas how I can remedy this? | When I run the command using a number - 2 which is the full backup profile no - instead of the profile name it does run. So this problem has been solved.
As a side note. I then I get this error: zip warning permission denied . I also see:
error - Error #3382: Backup FAILED. Unable to successfully generate ZIP archive.
error - Error #3382 help:
haltScript -
error - Failed function `backup_zip_files`. Backup terminated.
errorFunction - backup_zip_files
details - Peak memory usage: 42.82 MB
haltScript -
error - Sending email error notification with subject `BackupBuddy Error - to recipient(s): `[email protected]`.
details - Completed step function `backup_create_database_dump`.
Seems like hoster Dreamhost stops he script whether I use the plugin from the backend or the WP CLI.
But this new error is not related to the question asked. That one is solved. Just use a profile number instead of the profile name | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp cli"
} |
Do not display post images on front page
I have decided that for all pages where multiple posts are shown (e.g. front, category, tag pages), that post images should not be shown. Instead, featured images, if specified, should be shown next to each post.
Right now, featured images are working fine for posts. However, when multiple posts are displayed (e.g. on the front page, category pages), images should be stripped from the posts.
When a single post is displayed, the images should display as well.
I'm assuming that this has something to do with `add_filter()` and a regex `str_replace()` on the post, but this would affect the post no matter where it's displayed.
Reply | Try this
<?php
add_filter('the_content','wpi_image_content_filter',11);
function wpi_image_content_filter($content){
if (is_home() || is_front_page()){
$content = preg_replace("/<img[^>]+\>/i", "", $content);
}
return $content;
}
?>
Place in your functions.php file, call up your the_content() like normal. This will allow you to still have a feature image, but remove all images from main page. If you want to remove them from other pages just add to your and ||
\--Edit--
You were on the right track with the filter and replace, :) just have to do some digging. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, images"
} |
wp_mail recipient array not sending?
I am using wp_mail to send an email to multiple recipients.
my mail function looks like this:
wp_mail($group_emails, 'my subject', 'my message', $headers);
`$group_emails` is an array of email address's and gets outputed like this:
$group_emails = Array ( [0] => [email protected] [1] => [email protected] [2] => [email protected] [3] => [email protected] [4] => [email protected] [5] => [email protected] [6] => [email protected] [7] => [email protected] [8] => [email protected] [9] => [email protected] )
For some reason the email does not get sent to the above emails? If i remove the multiple recipients and just put a single email address, it works fine!
Any suggestions? | There are multiple ways of doing this.
You can consider any of the following.
1.My **preferred** :
foreach($group_emails as $email_address)
{
wp_mail($email_address, 'my subject', 'my message', $headers);
}
2.Another way
Define the array as follows.
$group_emails = array('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]' );
And then try your regular procedure:
wp_mail($group_emails, 'my subject', 'my message', $headers);
I am not sure about the second way. But the first way will work for sure. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "email, wp mail"
} |
How To Make Sure That My Action Hook Executes Last
How can I make sure that `my_function` action hook on 'wp_head' is executing last? One hack, that I'm using, is to give `999999` (a big number) as the third argument. But maybe some other hook on 'wp_head' is giving even bigger number than this one.
function my_function() {
?>
<style>
.custom-class{
background: blue;
}
</style>
<?php
}
add_action('wp_head', 'my_function', 999999); | You define priority. It's not a hack. Maybe it's that you're looking for is `PHP_INT_MAX` which is a PHP constant. So you can put it as priority number. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "hooks, actions, wp head"
} |
How can I change the label "Comments" to "Review" everywhere in the WP installation without translation
Got the way to change the labels everywhere for the post_type "Post". For a customer site, I need to use the WordPress comments. Just need to change the label from "Comments/Comment" to "Review" everywhere. But where for post_type "Post" we can use `$wp_post_types;`, what can we use for comments?
I tried with `$wp_comments`, `$wp_comment` etc. but failed.
How can I do it?
PS: I don't want a way to translate all the strings etc. Just need a way like the link pasted above. And not just the menu labels, I need to change them everywhere, so that under the post writing page, in the checkbox saying "All comments" would also change. | You can try the `gettext` filter.
According to the Codex:
> This filter hook is applied to the translated text by the internationalization functions (__(), _e(), _x(), etc.). This filter is always applied even if internationalization is not in effect, and if the text domain has not been loaded.
Here's an example:
function custom_gettext( $translated_text, $untranslated_text, $domain )
{
if( FALSE !== stripos( $untranslated_text, 'comment' ) )
{
$translated_text = str_ireplace( 'Comment', 'Review', $untranslated_text ) ;
}
return $translated_text;
}
is_admin() && add_filter( 'gettext', 'custom_gettext', 99, 3 );
to change the strings containing `Comment` to `Review` (ignoring case).
You can adjust the replacements to your needs. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "comments, labels"
} |
A refreshless WordPress website
As I said in my previous post, I am totally new in the WordPress world. My knowledge of PHP, Css, HTML and JavaScript is a little old but I am sure I can do this by my own with some guidance.
Please consider the image below:
!enter image description here
It consists of four main pages. By clicking on every category, new content will be loaded without the whole page getting refreshed every time.
Please help me. How should I do this in WordPress?
Loop functions, plugins, widget, even if you name your options, it would be a great help for me. | First there is bit of a snag in your terminology - "responsive" nowadays primarily refers to sites that adapt to screen sizes and is mostly unrelated to dynamically loaded content.
WordPress is not natively engineered for Ajax themes. It is of course possible and people do create such, but as percentage of overall theme building in ecosystem it's tiny.
In a nutshell you will have to pick technology for implementation first and make it play with WordPress second.
The common starting point is general info on using Ajax in WordPress and you might or might not want to go with Backbone.js framework which is included in WP core. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "ajax"
} |
Simple Redirect but getting the right code?
I need to change these links so the dashboard link directs to the forum profile instead of the wordpress admin panel profile can you help?
<ul>
<li><a href="<?php echo home_url() ?>/wp-admin/"><?php _e( 'Dashboard' , 'tie' ) ?> </a></li>
<li><a href="<?php echo home_url() ?>/wp-admin/profile.php"><?php _e( 'Your Profile' , 'tie' ) ?> </a></li>
<li><a href="<?php echo wp_logout_url(); ?>"><?php _e( 'Logout' , 'tie' ) ?> </a></li>
</ul>
apparently this guy has done it and it works with this code, however i don't know how to change
<li><a href="<?php echo home_url() ?>/wp-admin/"><?php _e( 'Dashboard' , 'tie' ) ?> </a></li>
to
<?php echo bbp_get_user_profile_url( get_current_user_id() ); ?> | Change line 1323 of your screenshot with the following:
<li><a href="<?php echo bbp_get_user_profile_url( get_current_user_id() );?>">Your Profile</a></li>
You can change "Your Profile" with different text if you like. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "redirect, code"
} |
How do I remove certain fields from the forum edit my profile page?
My users are able to click on their forum profile and edit things like their password and picture but I don't want some fields to appear. How can I get rid of: First Name, Last Name, Contact Info, Website, Blog Role and Forum Role? | The easiest way would be to edit the `form-user-edit.php` template located in `/templates/default/bbpress/` and remove the fields you do not want your users to be able to edit.
Make sure that you don't edit bbPress core files and copy the template to your themes `/bbpress` folder as outlined in the codex < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "bbpress"
} |
Display avatar with comment form?
I can display the current user's avatar alongside the comment form when posting a new comment with
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
echo get_avatar( $current_user->user_email, 32 );
}
,but how could I bind the avatar to the comment form if I want to reply to another comment when the onclick `addComment.moveForm` is fired? The avatar should move along with the form as it moves.
I would be very grateful if someone can point me in the right direction how to dynamically alter the comment form. Documentation on customizing the comment form at Wordpress.org is really poor and I have had a hard time finding any useful info around the internet as well. | I'll answer myself. Add the following somewhere in functions.php or make it into a plugin:
add_action( 'comment_form_logged_in_after', 'psot_comment_form_avatar' );
add_action( 'comment_form_after_fields', 'psot_comment_form_avatar' );
function psot_comment_form_avatar()
{
?>
<div class="comment-avatar">
<?php
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
echo get_avatar( $current_user->user_email, 32 );
}
?>
</div>
<?php
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments, comment form"
} |
How to update all post at once?
Is there a way to update all post at once?
The issue is, when i migrated content from another CMS, some of the permalinks are working fine and some of them are not, when i updated the posts all links are working fine.
I have tried some methods to perform this requirement, but it doesn't helped. | Thanks all,
The issue is resolved by removing special characters from wp_posts -> post_name.
Now all permalinks are working fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, slug"
} |
change register url on wp-login page
I am just trying to change the url of "register" on wp default login page(domain.com/wp-login.php)
1. I want to change the url on register link.
2. when you are on domain.com/wp-login.php?action=register, I want to redirect to domain.com/register
I have added redirect link. but it's not working.
RedirectMatch 301 /wp-login.php?action=register$
Am I missing something?
I just want to use my register page (domain.com/register/) | Code from @bainternet's website.
function wpse127636_register_url($link){
/*
Change wp registration url
*/
return str_replace(site_url('wp-login.php?action=register', 'login'),site_url('register', 'login'),$link);
}
add_filter('register','wpse127636_register_url');
function wpse127636_fix_register_urls($url, $path, $orig_scheme){
/*
Site URL hack to overwrite register url
*/
if ($orig_scheme !== 'login')
return $url;
if ($path == 'wp-login.php?action=register')
return site_url('register', 'login');
return $url;
}
add_filter('site_url', 'wpse127636_fix_register_urls', 10, 3); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp login form"
} |
How to have post count after each listed category
How can I have a post count after each listed category with the following function? Also, how can I apply this with wp_get_archives and also with the same option as the below function?
<ul>
<?php
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'number' => 10, // how many categories
);
$categories = get_categories($args);
foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in: %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> ›</li>';
}
?>
</ul>
Examples:
|(get_categories)
Category item 1 > ()
Category item 2 > ()
(wp_get_archives)
Archive item 1 > ()
Archive item 2 > () | For showing category count on your loop -
foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in: %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> › ('. $category->count .')</li>';
}
And for showing count with `wp_get_archives` function, use show_post_count in argument -
wp_get_archives( array( 'show_post_count' => true )); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, loop"
} |
wp_nav_menu $theme_location parameter ignored
This is the first paragraph of the documentation of the function `wp nav menu`:
> Given a `theme_location parameter`, the function displays the menu assigned to that location, or nothing if no such location exists or no menu is assigned to it.
However, I am providing a `theme_location` that I have not registered, and in spite of that a menu item appears.
Here's my functions.php:
<?php
function register_my_menu() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'register_my_menu' ); ?>
And here's how I call the menu:
<?php wp_nav_menu($args = array('theme_location' => 'nonsense')); ?>
On my page, a menu with the default item "Sample page" appears. According to the documentation I cite, nothing should be displayed, because the location "nonsense" should not exist.
Is the documentation wrong, or am I making some mistake? | The documentation is wrong. Check the source. There are two telling comments. First there is:
>
> // Get the nav menu based on the theme_location
>
And after which there is another comment that reads:
>
> // get the first menu that has items if we still can't find a menu
>
Following that last comment the code runs `wp_get_nav_menus` and loops through every menu on the site hoping to find one that has associated items. In other words, `wp_nav_menu` tries desperately to create a menu and will use the first one it finds. I don't understand the logic behind that code. I get the concept of fallbacks, but this strikes me as fallback overkill.
You will need to wrap your code in `has_nav_menu` to prevent this behavior.
if (has_nav_menu('nonsense')) {
wp_nav_menu(array('theme_location' => 'nonsense'));
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "menus, documentation"
} |
get_terms returns array starting at 4
I am using get terms to return a list of terms within a custom taxonomy. It's returning an array but it starts at index 4.
How do I get it to start at 0 like normal? | Run `get_terms` like this:
var_dump(get_terms('category',array('hide_empty'=>false)));
And then like this:
var_dump(get_terms('category'));
You should be able to infer what is happening. The first should return the zero based array you expect, with neatly numbered keys. The second does not. The only difference being the `hide_empty` argument.
If you really must have a zero based array just pass the results though PHP's `array_values`:
var_dump(array_values(get_terms('category'))); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
Backend of the WordPress.com
It has been known that PHP is under an impression that its a web low performer. However, the size of WordPress.com says otherwise. Does anyone knows why WordPress.com blogs scale so well even though its in PHP? Where is the PHP's maximum. Lets say capacity of simultaneous user access?
Thank You | Wordpress certainly can scale. Wordpress.com alone served 14.6 billion pages last month. The key is that they had hundreds of servers so that they can widely distribute the load. Since they have a more tightly controlled platform, which helps them ensure that they don't have badly written code slowing things down. But in the end, a lot of things don't have a limit to how large they can scale, as long as you give enough resources to it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, wordpress.com hosting, scale"
} |
New to CMS - WP functionality. overkill or just right?
I am a designer / developer. My experience is in HTML/CSS/JS, some knowledge in PHP, MySQL, and Wordpress one-click-install and pre-made template.
I want to program an entire website layout myself, and I have two places/needs for content management. (custom WP template?)
1. A media gallery in HTML/CSS/JS that can populate with images from a CMS image upload.
2. A series of 'profile cards' with fields I can customize in the CMS. A name, a title, a bio, an image etc. And then be able to display that content in customized HTML/CSS.
These two features, along with a well-designed intuitive admin panel are the requirements. In your opinion, can WP get this done and still allow me freedom in programming HTML/CSS layout? Sorry for general question, I really need some reassurance bc I'm very new to back-end CMS setup. | For the most part, I believe Wordpress will do just fine. You will have to brush up on your knowledge of PHP to get the hang of creating your own custom templates, but there are plenty of sites (This One Included) that will help guide you.
There are also a plethora of free & premium plugins for Wordpress (see CodeCanyon) that allow you to add many cool features to your site (Galleries, Image Sliders, Audio Players, Forms, E-Commerce stores..etc).
It will allow you to create "Custom Post Types" for your "Profile Cards" where you can list them on pages, create custom templates for them, and link them to specific users.
You can use ACF to add custom fields on any "Post Type", which can be called & displayed via the custom templates you make.
The admin panel is pretty straight forward and easy to learn how to use as well. I would recommend using some sort of pre-made skeleton theme or framework when making your first theme. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "html, cms"
} |
How to create a custom search form and handler?
I'm trying to build a search that, depending on what user chosen in admin, will either query one of several external api search methods with user input, save all the results in database and then display them or it will search the custom tables in database, it should also be fully encapsulated in a plugin. I already have the business logic that does this, I'm having trouble hooking it up to WP. What would be the best way to accomplish this?
edit: sorry, it was probably quite vague question, what I have is an app I described above built on php framework, what I want to do is move it to WP, the problem is while the logic itself will require little modification, I have no idea how to hook it up to wordpress via plugin, essentially how do I create a form with plugin and how do I take input from that form and direct it to the logic that will handle that request? | To change the search form, filter `get_search_form`. You get the form as a string here, and you can change it as you need.
add_filter( 'get_search_form', function( $form )
{
// Replace the form, add additional fields
return $form;
});
To change the search query to the database, filter `posts_search`. You get the query as a string and the current `WP_Query` object which provides more information. See `wp-includes/query.php` for context.
add_filter( 'posts_search', function( $search_query, $wp_query )
{
// change the SQL
return $search_query;
}, 10, 2 );
If you don’t want to filter the search query, change the `name` attribute in the search form, example `foo`, and inspect the `$_POST` request:
if ( ! empty ( $_POST['foo'] ) )
{
$global $wpdb;
$results = $wpdb->get_results( /* custom sql */ );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, search"
} |
Convert WordPress posts to products in WooCommerce
Is there anyway I could convert all the posts e have right now on our WordPress install into products using some MySQL query or something like that? | You could install the Post Type Switcher plugin
Or Run SQL query on your database to change the post to product post type
UPDATE `wp_posts` SET `post_type` = 'product' WHERE `post_type` = 'post';
**Backup your DB 1st.**
UPDATE `wp_posts` SET `post_type` = 'wpsc-product' WHERE `post_type` = 'post'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, mysql, e commerce"
} |
Should 'setup_postdata()' be reset with 'wp_reset_postdata()'?
Starting with an example makes more sense, so here's an example function:
function seo_meta_tags() {
global $post;
if( is_singular() ) {
setup_postdata( $post );
$description = str_replace( '... <a class="read-more" href="' . get_permalink() . '">Cont. reading →</a>', '...', get_the_excerpt() );
wp_reset_postdata();
echo '<meta itemprop="description" name="description" content="' . $description . '">';
}
}
_**NOTE:** The code is only to give you an idea of what I am trying to accomplish and not exactly how I am doing it._
Now coming to the point, should `setup_postdata( $post )` be closed with `wp_reset_postdata()` as shown in the example? | As `setup_postdata` is _messing_ with global variables that might be (most probably: **are** ) used by other loops (including _The Loop_ ), you should always reset these variables to what they should be--according to the main query (i.e., what WordPress thinks the user wanted in the first place).
In addition, `setup_postdata` is provided with (a reference to) the `$post` global, which might be altered afterwards.
So, yes, `setup_postdata` should be accompanied by `wp_reset_postdata`.
As you can see in the code, the `reset_postdata` function is, in fact, calling `setup_postdata` on the _original_ `$post` object. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "posts, wp query, query, wp reset postdata"
} |
Check if user is in a group of another site within multisite network
I'm using Woocommerce + the groups plugin on my main site to promote users to a 'Premium' group upon purchasing items which works great.
If a user on the main site then browses to the second site within my network, I can no longer check to see if they're within the 'Premium' group.
On my main site, I can use this code:
<?php
$user_id = get_current_user_id();
$group = Groups_Group::read_by_name( 'Premium' );
if ( Groups_User_Group::read( $user_id, $group->group_id ) ) {
?>
Premium content here!
<?php } ?>
But this does not work on the subsite. Is there anyway I can check to see if the user is in a group on my main site FROM a subsite? | Solved this with the following code:
<?php
$blog_id = 1; //set the blog id to the main site id
switch_to_blog( $blog_id );
$user_id = get_current_user_id();
$group = Groups_Group::read_by_name( 'Premium' );
if ( Groups_User_Group::read( $user_id, $group->group_id ) ) {
echo 'PREMIUM!!';
} else {
echo 'Not premium';
}
restore_current_blog();
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, multisite"
} |
Should I delete automatically-created files before installing WordPress?
I'm switching a site from OpenCart to WooCommerce.
I'm trying to figure out what I should delete from `public_html` and what I shouldn't.
Below are the files I'm unsure about. Some of them were there before I installed OpenCart (years ago), but I can't tell which ones.
Is it ok to delete all of them or should I keep some?
400.shtml
401.shtml
403.shtml
404.shtml
500.shtml
500.php
cgi-bin (empty folder)
default.html (empty)
error-log
php.ini | they are just index files and you can delete them, Wordpress will add its own index.php file.
php.ini is configuration file for php so you should keep it as it may be of some use. If you get any php related errors you can try deleting it too or we'll need to modify it... | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "installation"
} |
Can't install vEstate Real Estate WP Themes
I have downloaded the vEstate Real Estate WP Themes.when i try to install it I got this error.!enter image description here I have update the upload_max_filesize to 20M.plz tell how to fix this error? need quick help | WordPress themes are packaged in a .zip file format (not .rar). Theme Forest packages their items a little differently.
You likely need to decompress the .rar file (double-click on it). Inside will probably be another file called, vestate.zip. Try to upload that instead.
Also, in the future, support for this product should be handled via their designated channel. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "themes"
} |
add after content don't work
I am using this code to put some functions after content, but this one don't work. It appear before the content and not after.
function add_wb_posts_pagination ($content) {
$content .= wb_posts_pagination();
return $content;
}
add_filter('the_content', 'add_wb_posts_pagination' );
is the same code i use to add others functions, but this don't work...
what can be the problem? | `wb_posts_pagination()` seems to be a custom function that sends its output directly to the browser with `echo` or `print`.
Use a function that returns a **string** and does not create output to add that string to `$content`.
The printed output doesn’t wait, it goes into the page the moment you call that function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, content"
} |
Can I call Options Framework in footer.php?
I have integrated the Options Framework into my theme.
Can I call `of_get_option(...)` in footer.php? | You can call the function in any template file in your theme folder. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme options"
} |
Display pages from specific page template
Okay I have found the following code on line, which seems to be working and displaying all of the pages using the page_library_html.php template. This code only shows the title of them though. Can someone help me get the post content to show in as well as the title in .
Thanks in advance
**Current code**
<?php
$product_pages_args = array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page_library_html.php'
);
$product_pages = get_pages( $product_pages_args );
?>
<?php
foreach ( $product_pages as $product_page ) {
echo '<div id="posts" class="flex_100"><div id="library_title"><a href="' . get_permalink( $product_page->ID ) . '">' . $product_page->post_title . '</a>
</div></div>';
}
?> | Use `get_post_field('post_content', $product_page->ID )` to get the content outside loop.
<?php
$product_pages_args = array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page_library_html.php'
);
$product_pages = get_pages( $product_pages_args );
?>
<?php
foreach ( $product_pages as $product_page ) {
echo '<div id="posts" class="flex_100">';
echo '<div id="library_title"><a href="' . get_permalink( $product_page->ID ) . '">' . $product_page->post_title . '</a></div>';
echo '<div class="page-content">' . get_post_field('post_content', $product_page->ID ) . '</div></div>';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, css, page template, code"
} |
Show author name not the author ID
I have added the code to get the author, but it displays the author's ID number. How can I get the author's name to show and their gravatar.
**CODE**
<?php
$product_pages_args = array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page_library_html_content.php',
'hierarchical' => '0'
);
$product_pages = get_pages( $product_pages_args );
?>
<?php
foreach ( $product_pages as $product_page ) {
echo '<div id="posts" class="flex_100">';
echo '<div id="library_title"><a href="' . get_permalink( $product_page->ID ) . '">' . $product_page->post_title . '</a></div>';
echo '<div class="library-content">' . get_post_field('post_content', $product_page->ID ) . '</div>';
echo '<div class="library-author">' . get_post_field('post_author', $product_page->ID ) . '</div></div>';
}
?> | <?php
$product_pages_args = array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page_library_html_content.php',
'hierarchical' => '0'
);
$product_pages = get_pages( $product_pages_args );
?>
<?php
foreach ( $product_pages as $product_page ) {
$author_id = get_post_field('post_author', $product_page->ID );
$author_details = get_user_by( 'id', $author_id );
$author_name = $author_details->first_name . ' ' . $author_details->last_name;
echo '<div id="posts" class="flex_100">';
echo '<div id="library_title"><a href="' . get_permalink( $product_page->ID ) . '">' . $product_page->post_title . '</a></div>';
echo '<div class="library-content">' . get_post_field('post_content', $product_page->ID ) . '</div>';
echo '<div class="library-author">' . $author_name . '</div>';
echo get_avatar( $author_id , 32 );
echo '</div>';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, gravatar"
} |
get plugin directory url
I am trying to use SMOF Options Framework in a plugin and i have this problem. SMOOF use this constants to get theme directory url:
if( !defined('ADMIN_PATH') )
define( 'ADMIN_PATH', get_template_directory() . '/admin/' );
if( !defined('ADMIN_DIR') )
define( 'ADMIN_DIR', get_template_directory_uri() . '/admin/' );
But i want to use SMOF in a plugin, not in theme, how can i get the plugin directory url? What to put in order to get_template_directory() and get_template_directory_uri() to use it in a plugin? | Use `plugin_dir_url( __FILE__ );` for the URL and `plugin_dir_path( __FILE__ );` for the path.
Pass the plugin’s main file to both functions to get similar results.
Besides that, `ADMIN_PATH` and `ADMIN_DIR` are really poor names for custom code. They might result in collisions with other code in the future. Try to use better names, something with a unique prefix. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 2,
"tags": "plugin development, constants"
} |
do_action in header, add action later?
I want to include the facebook JSSDK only on pages where I want to use it. On the facebook dev site it sais that ideally its included right after the opening body tag, which sits in header.php
My thought was to add in header.php
<?php do_action( 'topofthetop'); ?>
right after the opening body tag.
And then later (in comments.php just before `<?php if ( have_comments() ) : ?>`), if I need to call
add_action( 'topofthetop', array('someclass','FB_JS_SDK') );
FB_JS_SDK simply echoes the code needed to included the FB-JSSDK. But the code doesn't appear after the body tag. I guess because header.php is allready output before my add_action call?
How could I solve this? | You must register callbacks before they are called (`add_action()` and `add_filter()` are registration functions, they remember what to do when).
Try the following in your `functions.php` or in your plugin:
add_action( 'topofthetop', 'load_FB_JS_SDK' );
function load_FB_JS_SDK()
{
if ( is_singular() && have_comments() )
someclass::FB_JS_SDK();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "actions"
} |
WP custom routing does not work
I am trying to get custom rounting on WP without any plugins. I have a bunch of links looks like this: <
I've created a page with slug = "userinfo" and added such code in function.php of theme:
add_action('init', function(){
add_rewrite_tag('%username%', '([^&]+)');
add_rewrite_rule('^u/([^/]+)/?', 'index.php?pagename=userinfo&username=$matches[1]', 'top');
}, 10);
This is not works (showing 404 wordpress page), meantime /index.php?pagename=userinfo&username=3323 works well.
What I am doing wrong?
Added: I made this working by changing permalink options to "default" and back to "custom". And it is works now. But I need an answer - how I can get new custom routes working without making this? | You have to flush rewrite rules after new rules are added. Visiting the permalinks settings page flushes the rules, which is why it worked after you did this. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, routing"
} |
Daily posts like an archive
I need to show 30 daily posts in the main page of a site. I also need to put 2 links, one that gets to a new page showing 30 posts made yesterday and the other to show 30 posts of 'tomorrow' if I'm looking at an older page.
I tried to use `wp_get_archives( array( 'type' => 'daily', 'limit' => 1 )`, but the thing is that now I have a page that shows a list of dates, and I need to click it to see the posts.
Is there a way form me to show the posts as soon as the visitor opens the site? | The function `wp_get_archives` as far as I know this will only output a list.
Instead use the WordPress loop and WP Query's Date parameters.
For example to get yesterdays posts using `WP_Query` you can do something like:
$yesterday = date('d.m.Y',strtotime("yesterday"));
$yesterdayarray = date_parse($yesterday);
$query = new WP_Query( '&day=' . $yesterdayarray["day"] );
// grab the data in the loop | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, archives"
} |
How does Wordpress resolve permalinks internally?
I am doing some deep modding of the rewrite system and custom post_types but before I can continue I must find out how WordPress handles the rewrites.
I found the function url_to_postid() but WordPress it self doesn't seam to use it to resolve permalinks into queries?
For example: If I hook into the pre_get_post functions, and browse a page or a custom post_type the provided query now include "is_page" or "attachment" etc but if i where to type a URL at random, this data will not show. Where does WordPress figure out if the URL is a page|posttype|attachment or not? And how can I hook into this? | If you have a look at the Action Reference, you'll see all of the actions executed before `pre_get_posts`. The two you'll probably want to investigate are `parse_request` and `parse_query` (yes, those are lacking in documentation).
The part you're probably most interested in is `parse_request`, where rewrite rules are matched against the requested URI. You can see it in source here.
When a front end request happens, the file `wp-blog-header.php` is loaded, which calls `wp()`, which calls the `main()` method of the `WP` class, which calls the `parse_request()` method. At the bottom of that function, you'll see where the `parse_request` action is executed.
**EDIT**
Also see this page in Codex for some more in-depth info: Query Overview | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "pluggable"
} |
how to limit edit_form_after_title hook to page and post edit only?
heelo, I want to use this great hook **edit_form_after_title**
it was announced on December 1, 2012:
<
**it curreclty hook for : post-new, post, page-new, page.**
how do I make it to work only in edit page/post ( **only post, page** )
thanks all | Personally I'd use a different approach, because **@Shazzad** 's solution seems too much global dependent, and **@s_ha_dum** 's needs 2 hooks instead of one.
I'd use `get_current_screen` function to get a `WP_Screen` object, then I'd look at its property to run (or not) something after the title:
function do_something_after_title() {
$scr = get_current_screen();
if ( ( $scr->base !== 'post' && $scr->base !== 'page' ) || $scr->action === 'add' )
return;
echo '<h2>After title only for post or page edit screen</h2>';
}
add_action( 'edit_form_after_title', 'do_something_after_title' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "posts, pages, hooks, editor"
} |
user_login vs. user_nicename
When you call the `get_users()` functions, a list of user objects are returned. Each of those users has a number of properties. What is the difference between `user_login` and `user_nicename` in those returned properties for each user? And which of those two properties are displayed in the URL? (I am asking because both properties are the same in my case!). | `user_nicename` is url sanitized version of `user_login`. In general, if you don't use any special characters in your login, then your nicename will always be the same as login. But if you enter email address in the login field during registration, then you will see the difference.
For instance, if your login is **[email protected]** then you will have **userexample-com** nicename and it will be used in author's urls (like author's archive, post permalink, etc). | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 18,
"tags": "users, user meta"
} |
Why does my sidebar get dragged down on this specific uid?
My sidebar is getting dragged down on uid=1: <
Now, the other contributor pages have the same underlying markup, yet they work fine.
For example, uid=3, <
I need to know what is happening and what should I do? | Look for unclosed elements like a div tag or unordered list tag which looks something like this:
/div>
/ul>
You've got 30 errors on the page and about 4 unclosed elements.
You can test any url using <
Here's some of the results:
Error Line 1277, Column 7: End tag for body seen, but there were unclosed elements.
Error Line 839, Column 33: Unclosed element div.
Error Line 739, Column 19: Unclosed element div. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "sidebar"
} |
taxonomy_template filter do not loads custom taxonomy template properly
I'm using taxonomy_template filter in my **plugin** to load a template file for **custom user taxonomies**. This is the code I'm using
add_filter( 'taxonomy_template', 'get_custom_taxonomy_template' );
function get_custom_taxonomy_template($template) {
$taxonomy = get_query_var('taxonomy');
if (strpos($taxonomy,'rcm_user_') !== false) {
$taxonomy_template = UT_TEMPLATES_URL ."user-taxonomy-template.php";
$file_headers = @get_headers($taxonomy_template);
if( $file_headers[0] != 'HTTP/1.0 404 Not Found'){
return $taxonomy_template;
}
}
return $template;
}
It loads the file but I get fatal error for wordpress functions like
get_header(), _e()
I've tried using default theme, saving permalink structures. | Issue was with `UT_TEMPLATES_URL`used for including the template.
I was using `file URL` and not `file PATH` which was creating the issue.
Modifying the `UT_TEMPLATES_URL`, to `FILE PATH` fixes the issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, custom taxonomy, templates"
} |
inner jQuery won't work
i'm enqueuing jQuery with `wp_enqueue_script( 'jquery' );`
(i see
<script type='text/javascript' src='
<script type='text/javascript' src='
in the resulting html page)
now, i'm tryin to use:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').slideToggle("fast");
});
});
and it only works if i add a jQuery reference manually (`<script src="//code.jquery.com/jquery-1.10.2.js"></script>`)
do i miss something? | Try this:
jQuery(document).ready(function() {
jQuery('#showmenu').click(function() {
jQuery('.menu').slideToggle("fast");
});
});
Wordpress hates the `$` statement. If you replace it with `jQuery`, it should work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Modify a plugin function output from another plugin
I'm writing a plugin for a wordpress site using a page template using WP Types plugin.
My plugin adds a shortcode tag.
Shortcode tags inside 'the_content' get processed without problem.
But this page template echoes `types_render_field(...)` WP Types function which gets and returns content containing shortcode tags retrieved from the database using `get_post_custom($postid)` wordpress core function call.
I want to process these shortcode tags without modifying the template or WP Types plugin, just using my plugin code.
Is that possible? | I will never understand the point of these wildly complicated "helper" wrapper/plugins... but that aside...
The plugin provides a lot of filters that might help you out. I think that the `types_view` filter might be what you want. Something like this is a plugin file or your theme `functions.php` might do it:
add_filter('types_view','do_shortcode');
I do not use that plugin, have never used that plugin, and I am guessing-- a lot-- but I hope that helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, plugin development, filters, shortcode, plugin types"
} |
how to redirect to a custom post template
I'm building a website in which there is a page where I collect a list of works/projects; I created a file called `work.php` where I made the template of this page, but when I try to view a single custom post (when I press on a single item), it says that the page doesn't exist.
Then, my question is: do I have to create a custom template like `work-post.php` for the custom post or do I have to use `single.php`?
P.S. I'm using a custom post called `work` type I made. | If you CPT is called " **work** ", i.e. you have registered it using
register_post_type('work', $args);
you have to create a file called **`'single-work.php'`** and that will be used to show the singular work post.
If you don't create that file the file `'single.php'`,if present, will be used by WordPress. If even the `'single.php'` does not exist in your theme, then the `'index.php'` file will be used.
Please see **WordPress Template Hierarchy** on Codex for more info. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, posts"
} |
Displaying year once in category.php
I want to be able to make my category.php display like this:
2013
Title 3
Title 2
Title 1
2012
Title 3
Title 2
Title 1
It's already been done for displaying ALL posts but how do I get it to display only the category being viewed?
Any assistance would be appreciated.
Thank you! | Create your query for the category, and order by date
$q = new WP_Query('category_name=acategory&orderby=date&order=DESC');
After that, while looping posts, save the year in a helper variable, shoing it only when changed:
$year = 0;
if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post();
$post_year = (int) get_the_time('Y');
if ( $post_year !== (int) $year ) {
echo '<h2>' . $post_year . '</h2>';
$year = $post_year;
}
// the loop
echo '<p><a href="' . get_permalink() . '">' . get_the_title() . '</a></p>';
endwhile;
endif;
wp_reset_postdata();
unset($year, $post_year); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, templates, archives"
} |
delete value 0 in post meta
I have a simple question. I have this code and its correct,
<?php global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'codigopostal', true);
if($meta != $empty) { echo "(".$meta.")"; } ?>
but when the user don't put nothing, value is 0. I want delete that value on frontpage.
<?php global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'codigopostal', true);
if($meta != $empty) {
echo "(".$meta.")";
}
else if($meta != 0) {
echo "";
}
?>
I added else if... but is wrong. | This question is off-topic because your is a simple PHP error, not related to WordPress.
You are trying to check if a variable is empty using:
if ( $meta != $empty ) {
but this is not the right way, in fact this code compare the target variable `$meta` with another variable `$empty` that is not defined.
If you want to check if a variable is empty in PHP you have to use the `empty` function so your code should be:
<?php
$postid = get_queried_object_id();
$meta = get_post_meta($postid, 'codigopostal', true);
if ( ! empty($meta) ) echo "(" . $meta . ")";
?>
Note I've used `get_queried_object_id` that return the id of the current queried post id without using global variables. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta"
} |
Adding CSS to Blog Posts?
How do you add CSS code to a certain blog post in WordPress? Would I have to create a new file and keep the CSS code I need for this blog post in that file? | You can use PHP code in your child themes functions.php file to add a custom body class to any page/post etc.
add_filter( 'body_class', 'my_custom_body_class' );
function my_custom_body_class( $classes ) {
if ( is_single( '007' ))
$classes[] = 'custom-class';
return $classes;
}
This sample code will add a custom body class to the post with i.d of 007 so you can style that specific post in your child themes style.css file.
Sample CSS:
.custom-class {
font-size: 20px;
}
Source < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css"
} |
How to set path with WP_Filesystem and ftp base / chroot
In my theme i will use the WP_Filesystem to write a file to for example:
$file = get_template_directory().'/library/assets/css/wpless2css.css';
Which outputs something like `/home/user/domain/http_docs/wp-contents/theme/mytheme/library/assets/css/wpless2css.css`
This will work unless the ftp user will be chroot to `/home/user/domain/` (on some servers?).
In the case of a chroot the WP_Filesystem can't find `$file`.
A solution seems to define `FTP_PATH` in wp-config.php into `/home/user/domain/` and use:
if(FTP_BASE) $file = str_replace(FTP_BASE,'',get_template_directory()).'/library/assets/css/wpless2css.css';
I'm looking for a solution more robust and support for the different possible permissions systems. | After changing `FTP_BASE` in my `wp-config` i found the update function of WP broken. Then i realize the update function work the same way and don't need any additional settings. In `wp-admin/includes/update-core.php` i found the usage of `$wp_filesystem->wp_content_dir()`. This solves my problem too.
On < you will find a list of possible useful functions:
string wp_content_dir ()
string wp_lang_dir ()
string wp_plugins_dir ()
string wp_themes_dir ([string $theme = false])
In fact @otto give my the answer earlier (Using wp_filesystem in Plugins), here he wrote:
> When using the $wp_filesystem, there's a handy function call for getting the content directory path: $wp_filesystem->wp_content_dir();. You need to use this function because the "remote" directory path may not be the same as the "local" directory path. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "theme development, ftp, filesystem api"
} |
Using Templates with Custom Post Type UI
I'm using this nifty little plugin called Custom Post Type UI to add custom post types to my WordPress site and am having a little trouble working out the best way to apply a page template to my custom post types.
Does anyone know the best way to achieve this?
Any help is appreciated. Thanks in advance! | WordPress has a built-in template hierarchy that determines what template file will be loaded for a given type of post or page. If you have a look at the visual overview of the hierarchy, you'll find that custom posts have their own specific entries. For example, if your custom post type is named `book`, then a single post's template will be `single-book.php` if it exists, `single.php` if it does not. (`index.php` is the global fallback -- a theme really only _needs_ to contain `style.css` and `index.php` to function.)
Any desired template files (ie, `single-{$posttype}.php`) should be added to your active theme.
### References
* Post Types
* Template Hierarchy | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "custom post types, templates"
} |
Can't un-archive site after upgrading to Wordpress 3.8
After upgrading to Wordpress 3.8, both of my network sites were archived.
I could un-archive one, but the other has no option to un-archive in the Sites list:
!enter image description here | * go to php my admin
* click on database name
* go to wp_blogs
* see the column named archive
* You will see the value as 1 in this column. change it to 0 and save.
* everything will become fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
Wrong IP address in comment section
I have noticed that the last few times in which I have linked to an old post of mine from my latest post, my IP address in the Comments section is wrong (sometimes my IP address appears in the form 192.x.x.x).
Since I am not proxied or anything, why does this happen? | I assume that by comment you actually mean a trackback/pingback. Those are sent from your server and not your computer and since in this case it sent from your server to itself it probably uses the local IP for the communication. 192.X.X.X is an IP range reserved for local in LAN communication same as the 10.X.X.X range. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
wp_nav_menu inside an object -- how do I deal with fallback_cb?
I'm trying to create a class that allows me to generate a navigation menu. Here's a simplified version of what I'm using:
class PJ_Menu {
function make_menu() {
$args = array(
'theme_location' => 'location',
'fallback_cb' => array( $this, 'pj_page_menu' ),
);
wp_nav_menu( $args );
}
function pj_page_menu() {
// a bunch of code here
}
}
new PJ_Menu();
I can't seem to work out what I need in the `fallback_cb` parameter. `array( $this, 'pj_page_menu' );` didn't work, and neither did `'self::pj_page_menu'`. Am I missing something obvious, or is it not possible to do this? | The `fallback_cb` argument is used when the menu doesn't exist-- that is, when there is no menu of the right name. I won't be used otherwise. Check the Codex. By default the fallback is `wp_page_menu`.
Your code looks right to me for using a class method as the callback, but I suspect that what you really want is the `walker` argument, not the `fallback_cb` one. The `walker` argument will be used any time that your menu is created, not just as a fallback if something goes wrong. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, oop"
} |
Customizing the Widget content markup
I am using bootstrap to create panels for the sidebar widgets, and I can set the container markup for the widget, as well as the markup for the panel header, but I cannot provide the markup for the panel content. I have this so far:
register_sidebar(array(
'name' => __('Right Sidebar'),
'id' => 'home_right_1',
'before_widget' => '<div class="panel panel-default">',
'after_widget' => '</div>',
'before_title' => '<div class="panel-heading"><h3 class="panel-title">',
'after_title' => '</h3></div>'
));
bootstrap panels need to look like this:
<div class="panel panel-default">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
Panel content
</div>
</div>
How can I add the '<div class="panel-body">###</div>' to each widget? | Add:
* opening `<div class="panel-body">` to the end of `after_title`
* closing `</div>` to the start of `after_widget`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, widgets, twitter bootstrap"
} |
get_post_meta inside echo
I have a serious problem :)
I have this code:
<?php global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'provinciadestacada', true); ?>
And i want include here:
<?php if ( in_category( '951' )) { echo 'Online'; }
else
?>
After else i want get post_meta "provinciadestacada"
Maybe something like this?
<?php if ( in_category( '951' )) {
echo 'Online. Todas las provincias'; }
else echo "global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'provinciadestacada', true);"
?> | Use it like this
<?php if ( in_category( '951' )) {
echo 'Online. Todas las provincias'; }
else {
global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'provinciadestacada', true);
echo $meta;
}
?>
To do it in reverse as you want:
global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'provinciadestacada', true);
if(!empty($meta)) {
echo $meta;
}
elseif(in_category( '951' )) {
echo 'Todas las provincias';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
Adding page subdirectory dynamically, as like buddypress does
I have a page with slug/name **charts**. So the url looks like ` for the Charts page. When i type the url to ` or ` i got error not found, logically it should as there is no sub page with the given names.
Now what is want is, when is visit to ` or ` it should still query the Charts page, and also add the single or multiple occurred `(something)` into wp query var so that i can access it with get_query_var function. The (something) would return as an array ofcourse.
The `(something)` could be any Alphanumeric characters, and not needed to be a valid one. Just need it so that WordPress Still makes query for the Chart page, and all the extra url path are added to wp_query Object.
Your help is strongly needed. | This should do what you want:
add_action('generate_rewrite_rules', 'wpse128082_add_rewrite_rule');
function wpse128082_add_rewrite_rule($wp_rewrite) {
$new_rules = array(
'^charts/(.*)' => 'index.php?pagename=charts&something='.$wp_rewrite->preg_index(1),
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_filter('query_vars', 'wpse128082_add_query_var');
function wpse128082_add_query_var($query_vars) {
$query_vars[] = 'something';
return $query_vars;
}
On your _Charts_ page, you can access the new query var with `get_query_var('something')`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query"
} |
Conditional loading of CSS for my plugin
I'd like to continually load the stylesheet needed by my plugin depending on whether a particular shortcode is present on the post or page. The presence of the shortcode would indicate that the user is using the plugin on that post or page and therefore we need to load the JS and CSS. Is this possible? | Since WP 3.3 you can use `wp_enqueue_*()` after `wp_head`, and enqueued scripts and styles (if not already added to the `head` of the page) would be loaded in the footer.
In short just call `wp_enqueue_script()` / `wp_enqueue_style()` in your shortcode callback:
add_shortcode( 'my_shortcode', 'my_shortcode_callback' );
function my_shortcode_callback(){
//Shortcode does something, and generates mark-up to return
$html = '';
//Enqueue scripts / styles
wp_enqueue_script( 'my-script' );
wp_enqueue_style( 'my-script' );
return $html;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional content"
} |
Plugin Scripts no loading on options page
I've got this in my main php file, but the scripts aren't loading
function class_table_scripts() {
wp_register_script( 'JavaScript1', plugins_url('js/wcs.js'), array() );
wp_register_script( 'JavaScript1', plugins_url('js/jquery.qtip-1.0.0-rc3.min.js'), array('jquery') );
}
add_action( 'wp_enqueue_scripts', 'class_table_scripts' );
I've never tried to use JS or JQuery on the options page before, this is my first go. Any pointers on where I'm going wrong here?
* * *
EDIT: Here's what finally worked for me:
function class_table_scripts() {
wp_register_script( 'JavaScript1', plugins_url('js/wcs.js',__FILE__));
wp_register_script( 'JQuery1', plugins_url('js/jquery.qtip-1.0.0-rc3.min.js',__FILE__) );
}
add_action( 'admin_init', 'class_table_scripts' ); | Here's how I finally got it:
function class_table_scripts() {
wp_register_script( 'JavaScript1', plugins_url('js/wcs.js',__FILE__));
wp_register_script( 'JQuery1', plugins_url('js/jquery.qtip-1.0.0-rc3.min.js',__FILE__) );
}
add_action( 'admin_init', 'class_table_scripts' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, javascript, actions, wp enqueue script"
} |
Plugin alternative to Normalize.CSS?
Hello Wordpress world!
Since Normalize.CSS is not actually a wordpress plugin, could someone recommend me something close to it?
Thanks! | Something like this maybe close to what you need < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins"
} |
Getting category before saving post
I am using the filter "wp_insert_post_data" to decide what to save to the database. I need to know which category has been picked before saving the post.
How can I get to know the category that has been picked while using that filter? Is there a $_POST["category"] like variable or category object accessible at this phase? | Yes, and you're quite close to it. Just use the `$postarr` parameter of this filter:
add_filter( 'wp_insert_post_data' , 'wpse128138_wp_insert_post_data', 99, 2 );
function wpse128138_wp_insert_post_data( $data, $postarr ) {
// run this only for posts
if ( 'post' != $postarr['post_type'] )
return $data;
foreach( $postarr['post_category'] as $category_id ) {
if ( is_wp_error( $category = get_category( $category_id ) ) )
continue; // invalid category, just pass
// and here you can safely use the $category object
}
return $data;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "categories"
} |
How to create a post with next buttons
I am trying to create a post to show top 10 movies of 2013.
I have created a post with the same heading. However how can I show the post with next buttons. That is position 10 movie should be first, with corresponding image and some text.
Then on clicking next button go to 9th movie. like that the last screen should be the 1st movie.
Is there any plugins available? or how can I achieve it. | WordPress has Page-Links links feature that allows to easily and natively split single post into multiple pages.
The pages are separated using `<!--nextpage-->` tag and normally theme should automatically handle output, using `wp_link_pages()` template tag. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Exact image sizes
I am trying to define an image size of exactly 290 height x 180 width for all images uploaded to my WP site. I tried updating image sizes under Settings->Media->Image Sizes but these are only max values and some images end up coming out at 290 x 155 etc, is there a way to force WP to create an image at my desired size?
I am not using post thumbnails, I have built a plugin that uses wp_get_attachment_image() to retrieve images. | You'll want to use add_image_size() in your functions.php to tell Wordpress you'd like it to create a new image size when you upload images:
`add_image_size( 'custom_image_size_name', 290, 180, true );`
Using the value true will tell Wordpress you want it to crop the image to those exact dimensions.
Once you do that and upload an image, you can use `'custom_image_size_name'` in `wp_get_attachment_image()` to get the correct image.
Because Wordpress only creates the image sizes when you upload images, you'll want to use a plugin like AJAX Thumbnail Rebuild to rebuild previously uploaded images with your newly defined images size. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "attachments, images"
} |
Page Automatically Generated from Theme?
I'm running WordPress multisite and would like each site to have a specific page (with pre-loaded content) generated from a page template, contact.php. Rather than go through each site and create this page, I would like it to be created automatically by the theme. I plan to add all the content in contact.php itself. I'm assuming there is a way I can do this with a theme hack but have no idea where to start.
To put it more simply, the theme would automatically create a page at domain.com/contact from the template contact.php. | Put this in your `functions.php` file:
$contact_query = new WP_Query(array(
'pagename' => 'contact',
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => 1,
));
if (! $contact_query->post_count)
wp_insert_post(array(
'post_name' => 'contact',
'post_title' => 'Contact',
'post_status' => 'publish',
'post_type' => 'page',
'post_author' => 1,
'page_template' => 'page-contact.php',
));
unset($contact_query);
**What does it do?**
If the contact page does not exist, create it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, pages, page template"
} |
Where is defined a custom register_taxonomy?
Where is defined a custom register_taxonomy for my website url?
Now is showing:
But I want
In which file I change this? | Can you use any plugin for this url ? Or Made page or post or category for this URL ? What to do ? How you generate this url ?
If you are using any plugin, you can see plugin functions.php file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, urls"
} |
Email notification
Im trying to enrich this notification with subject (post title) and content, rather than its current view and edit links, could anyone help?
<?php
function __notify_admin_on_publish( $new_status, $old_status, $ticket )
{
if ( $new_status != 'publish' || $old_status == 'publish' )
return;
$message = 'View it: ' . get_permalink( $ticket->ID ) . "\nEdit it: " . get_edit_post_link( $ticket->ID );
if ( $post_type = get_post_type_object( $ticket->post_type ) )
wp_mail( get_option( 'admin_email' ), 'New ' . $post_type->labels->singular_name, $message );
}
add_action( 'transition_post_status', '__notify_admin_on_publish', 10, 3 );
?> | `$ticket` is a `WP_Post` object. It should have all of the information you need. Just add that information to the `$message` string to create whatever content you want. Bare-bones example:
$message = 'You are viewing '.$ticket->post_title;
$message .= 'Post Content: '.$ticket->post_content;
$message .= 'View it: ' . get_permalink( $ticket->ID ) . "\nEdit it: " . get_edit_post_link( $ticket->ID );
If that isn't what you are looking for, I am certain I don't understand the question. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email"
} |
Determine category in taxonomy of current custom post type
Using a php statement - how can I determine the name of the category in a taxonomy of the current custom post type that a user is browsing? | `get_the_category` is the most obvious answer. Per the Codex:
> Returns an array of objects, one object for each category assigned to the post. This tag may be used outside The Loop by passing a post id as the parameter.
Or `wp_get_post_categories` as in this example from the Codex:
$post_categories = wp_get_post_categories( $post_id );
$cats = array();
foreach($post_categories as $c){
$cat = get_category( $c );
$cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}
But your question is _very_ light on detail. It is hard to tell exactly what you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom post types, custom taxonomy"
} |
Speed optimization on WP site, Remove query strings from static resources
I am using GTMetrix to test the speed of one of my sites. The report says that I should 'Remove query strings from static resources'
Resources with a "?" in the URL are not cached by some proxy caching servers. Remove the query string and encode the parameters into the URL for the following resources...
How can I do that and is it recommended? | IMO it is recommended to ignore 50% of the google speedtest recommendations, this is one of them
> Resources with a "?" in the URL are not cached by some proxy caching servers. Remove the query string and encode the parameters into the URL for the following resources...
Maybe it was true in 2005 but now I wish google would have specified exactly which are they. In any case the chances of any page of any small or medium site to be cached and reused from the cache is minimal. The effort you might need to put in rearranging the urls of your static resources is not worth the zero speed improvement your site will gain. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "performance"
} |
rt media plugin count not working in shortcode
I used rtMedia plugin in my buddypress site. I used the short code `<?php echo do_shortcode('[rtmedia_gallery global="true" media_type="all" count="4" loadmore="false"]'); ?>` to dispaly media gallery items. But the count and load more not working. It shows more than 4 items now. How to fix this? | As of now rtMedia Gallery shortcode `rtmedia_gallery`, doesn't support `count` as it's attribute.
In order to limit the number of media, you have to change the media count from rtMedia Settings. Here is the screenshot:
!enter image description here
You just need to set a desired value for media items in the input.
Also you can directly ask rtMedia related questions on the support forum for plugin, it's quite active. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, buddypress"
} |
Prevent post from being published if no category selected
I do not want a user to be able to publish a post if no category is selected. I don't mind throwing a JS alert or handling this on the server side as well.
Anyway, how can I ensure this?
Note: "uncategorized" should not be chosen as well. | You can do this easily with jQuery:
/* Checks if cat is selected when publish button is clicked */
jQuery( '#submitdiv' ).on( 'click', '#publish', function( e ) {
var $checked = jQuery( '#category-all li input:checked' );
//Checks if cat is selected
if( $checked.length <= 0 ) {
alert( "Please Select atleast one category" );
return false;
} else {
return true;
}
} );
The above code will show an alert box if no category is selected. You can use dialog box instead if you'd like. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "posts, publish"
} |
How to disable (get rid of) home page main loop entirely?
I'm using a custom theme, the index page doesn't depend on the main loop for home (which by default get the latest 10 posts for example).
How can I get rid of the home loop entirely, so the index doesn't request any additional data from the database? | "The Loop" is WordPress. Trying to get rid of it is impossible. It may return no results, but it will always be called.
That being said, it does not mean that you have to call a listing of posts on your home page. If you instead plan on customizing the front page to be "static content" (ie. a "Page"), then you can use the WordPress Template Hierarchy to change the way it works.
Create a template called "front-page.php" in your theme directory that will still run/display the loop. Then in the Administration panel under Settings->Reading, where it says "Front page displays", select the radio button for "A static page (select below)". You can then use that Page to modify the content area of your home page template.
You can read more about the Template Hierarchy here... < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database, homepage"
} |
How to translate "Permanent link to" text
My theme contains the following to create permalinks:
<h3><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
However I want to translate the "Permanent link to" text.
How do I do that?
Thank you. | one possible way:
<?php
$link_text = sprintf(
__( 'Permanent link to %s', 'youthemetextdomain'),
get_the_title() ); ?>
<h3><a
href='<?php the_permalink(); ?>'
title='<?php the_title_attribute(); ?>'
><?php echo $link_text; ?></a></h3>
get_the_title() returns the title instead of displaying it. The double-underscore function is how WordPress allows strings to be extracted from a theme or plugin for translation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
Can I just copy and duplicate a WordPress installation?
I have a virtual server at Strato with Plesk 11 installed. There I got offered to install WordPress and created a blog. All fine. It has created a "/wordpress" folder on my server's `httpdocs` directory. Say, I wanted to have a second installation of WordPress on the same server, running a different blog. Can I just go and duplicate the WordPress subdirectory? Is everything that is needed for WordPress inside that folder? | You would end up with broken links if you simply copied the files over to a new folder.
What you would need to do to avoid this is install a plugin like WP Migrate DB and enter in the new server path.
You would then need to create another database taking note of the name, username and password which you would need to change in the wp-config.php file of the new installation.
If its a new site without any content or customization, you would be better off to simply install a new version of WorPress in a new folder on your server.
Here's the way to install WordPress manually. <
There are also plugins like duplicator which maybe useful to you.
Resources < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
Installing multisite on domain with existing subdirectory wordpress installations
I have a domain that already has a number of wordpress installations in existing subdirectories.
I would like to activate wordpress multisite to manage so new subdirectory installations with a new template.
The concern I have is that on activating multisite it's prompting me to clear all database tables for the existing installation. Will this cause a problem for the 20+ existing installations? | Typically, each instance of Wordpress has it's own database. If you have 20+ seperate Wordpress installs, then you should have 20+ different databases. Each database is going to have quite a few tables.
If it is asking you to clear the database _tables_ , then it is most likely only referring to the data for a single Wordpress install: namely, the one your are installing Multisite on. In other words, your 20+ other Wordpress installations should be safe.
However, when installing Multisite, it is _always_ a good idea to back up your databases.
As far as using it to manage your sites, I'm not sure if multisite is the best solution. There are plenty of plugins that will perform the function you need, without having to manipulate databases. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "multisite, directory"
} |
Add unique class or ID information to tinyMCE
Is there a method to apply a unique body class ID to the editor in the same way that body class information is added to the published page?
I am using the add_editor_style() function to render the editor's styles to reflect the published page. However, there are some pages where the styles break away from the standard page rules, and I would love to be able to include some of those exceptional style rules in the editor. | You can filter the TinyMCE body classes to add or change as needed. It's a string that's pre-populated with some things like post type, so the easiest thing to do is append your additional classes (with a preceding space).
<?php
function wpse_128380_tinymce_body_class( $mce ) {
// you could do things here to detect whatever you need
// and use those for the additional classes.
// be safe and use sanitize_html_class or similar if generated.
// example: use the post ID when editing a post
if ( $post = get_post() ) {
$mce['body_class'] .= ' ' . sanitize_html_class( $post->ID );
}
$mce['body_class'] .= ' custom-class another-custom-class etc';
return $mce;
}
add_filter( 'tiny_mce_before_init', 'wpse_128380_tinymce_body_class' );
// if you're using the "teeny" version of the editor,
// it fires the teeny_mce_before_init filter instead. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 4,
"tags": "tinymce, wp editor"
} |
Taxonomy landing pages
I like to create a landing page for my custom taxonomies. Right now ive created three custom taxonomies
/country/[terms]
/person/[terms]
/interrests/[terms]
i like to create a listing page for each of the taxonomy, this listing page should list all the [terms] they contain. And link to the normal (`taxonomy-[term].php` `/taxonomy/[term]`) url. What is a proper way to implement this?
First i was thinking something along the lines with template_redirect and create a custom `taxonomy-list.php` file to include in the action which manually query using a `WP_Query()` | I can see at least 3 ways to do that.
1. Adding a rewrite rule. See < for details:
add_rewrite_rule('^(country|person|interest)/?','index.php?tax=$matches[1]','top');
then use the `template_redirect` filter to load your template when the `tax`variable is there:
if (get_query_var('tax')) {
# load the template here
}
You'll also need to add the `tax` query var to the list of filtered vars using the `query_vars` filter.
2. Creating pages using specific template to list the terms
3. Creating pages and use a shortcode to list the terms | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom taxonomy, template hierarchy"
} |
When is it appropriate to put functions on page template vs. functions.php?
I'd like to improve my code and on a current theme, I've extended Wordpress with custom post types, metadata, customized user authentication, and a number of other items.
Some of these functions exist in the functions.php file while I've put others directly on the template files that they relate to. I have little reason for doing this initially, other than it seemed appropriate because said template file was the only file using the specific function.
But I'd like to know what is considered best practice for the sake of speed and security? What do you do? | If it is a custom theme for your site then there would no great speed or security improvements by moving functions.
On the other hand if you want to distribute the theme then I recommend having only the minimum php in the page templates files and having the rest of the functions organized in different files. I like the basic theme set up files of the theme to be in the functions.php and the rest in separate organized files. _s does a good job of this. The reason for moving the functions away from the templates files is that it makes it easier to customize and manage. If you need to duplicate a template then you do not end up duplicating functionality.
I would even place the non-presentational functions in a plugin for easy deactivation and management. See this answer for more information. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "plugin development, functions, customization, templates"
} |
How to create a page for authors? like www.myblog.com/author/
I have **author.php** and it's working fine for authors separately.
**eg:**
* if I click **author1** and it goes to `www.myblog.com/author/author1` and shows his details
* if I click **author2** and it goes to `www.myblog.com/author/author2` and shows his details
Now I want to show all these users under 1 url like `www.myblog.com/author/author` If somone goes to `www.myblog.com/author/author/`then it should show the authors list with their details.
How can I do that.? Any help will be very much appreciated.
Thanks. | A bit like a team/contributors page.
You could look at the contributors page template included in the Twenty Fourteen default theme for WordPress as an excellent example. May be a challenge to use it with another theme depending on your skill level.
Another option which i have coded myself for Genesis, is a widgetized page template. This way you can use any type of author/profile widget in the widget areas. No author details are hard coded so you simply add a new widget each time you use a new author.
You could also code a page template with widgets which works with any theme. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "urls, author"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.