INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
In a MS install, can you allow different users to have their own themes?
Is it possible in a MS install to allow network site admins to edit their own themes? For example, I would like to give everyone access to theme ABC, but if one user edits that theme, they seamlessly create their own instance of the theme, so no other user's theme is affected. I believe the short answer is "no" so I'm wondering if there are any good ideas about how to implement this kind of system. | Well as WordPress is open source, if you have control of your server, you can technically do anything :-) Depending on your skill set, that may or may not be feasible.
A low tech solution would be to create a copy of the theme ABC for each user. Change the folder name, and change the **Theme Name** in the comment at the top of style.css to personalise it to each user (e.g. "ABC for Bob", "ABC for Clare"). The codex on child themes is a good starting point for information about this.
I'm not aware of any API calls to detect changes through the theme editor, so I think you'd have to patch the core WordPress install. I had a brief search for where this might be. Using exec() to copy the theme directory would be pretty simple, but the user interaction and updating which version of the theme is being used could make it a bit more complicated.
Of course this is further complicated by the fact that the 'edit' function on a multisite is only available to the network admins. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, themes"
} |
How to call uninstall.php?
I am a newbie in WordPress... I have created my plugin... now i am creating uninstall.php file for uninstall my plugin...
this is my code of uninstall.php
if(!defined('WP_UNINSTALL_PLUGIN'))
exit ();
//here I am dropping my table and options...
I don't know how to call uninstall.php? from where to call? from where i can uninstall my plugin...
I know register_uninstall_hook() but when it get triggered?
Thanks in advance | Uninstall hook and `uninstall.php` file are two alternate ways to implement uninstall functionality, they are independent of each other.
When `uninstall_plugin()` is called it checks for `uninstall.php` **or** hook (in this order).
So if you are using file approach there is nothing special you need to do to call it. WordPress looks it's up by name and runs on uninstall natively. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Adding Sidebars in WordPress Theme
Can anyone help me on how to add two sidebars on the main page of my WordPress site. I need one on the left and the right. I'm new to WordPress and don't know much about the code, even when I tried reading the codex. My website is here I am using a Ready To be theme, with Ready E-Commerce plugin | Use this in your funtions.php to register sidebar
if ( function_exists('register_sidebar') )
register_sidebar(array('name'=>'Sidebar ',
'id'=>'sidebar',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<p>',
'after_title' => '</p>',
));
To use it in your theme use the following
<?php
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar') ) :
endif;
?>
Refer this to know more : < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, sidebar"
} |
Add more levels to menu
I have a menu with more than three levels.
The issue is that the menu just shows until level 2, the next child levels don't show. I am using Maya template and WordPress 3.5.2
What i have to do and what file i must edit to make this work?
Thanks for your help.
EDIT
Go to wp-content/themes/templatename/ and then in header.php go to his line
'depth' => apply_filters( 'yiw_main_menu_depth', 3),
Just change the number and done! | Go to wp-content/themes/templatename/ and then in header.php go to his line
'depth' => apply_filters( 'yiw_main_menu_depth', 3),
Just change the number and done! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Media Editor uppercase extensions to lowercase
What's the reason for making the extensions on uploaded images lowercase as soon as the upload is complete? | File names on UNIX or Linux are case sensitive. Rewrite rules or the simple check for duplicate file names are much more reliable when the extensions are unified during the file upload. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Getting error “The package could not be installed. PCLZIP_ERR_BAD_FORMAT ”
i am newbie in wordpress. i have created my own plugin and it's working fine for me... now i have created rar/zip file my plugin folder... i am uploading my plugin .rar file in my another wordpress project...
it's giving error
The package could not be installed. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature
through FTP it's working fine in my all wordpress projects... but i want to make it uploadable.
my plugin file structure is :--
/mypluging_dir
**--images---**
**--css--**
**--pluginfile.php--**
**--abc.php--**
**--xyz.php--**
i am using xampp 3.2.1 and my wordpress version is 3.7.1
Any help will be appreciate..
Thanks in advance | As the wordpress standard you have to upload **.zip** file only... as you mentioned in your question **.rar**.. it won't get upload...
Try to convert in to the **.zip** format and try... surely it will get upload...
after that if still you are getting error let me know..
hope it may help you... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Change the name of an installed plugin
I have installed a third-party plugin for my wordpress site. What I want is to rename that plugin so that it matches my purpose for installing it. Is it possible?
The plugin I'm trying to modify is CubePoints.. It's a pointing system for the users. But for the sake of better understanding, I'll be calling it MyPoints or something like that.a
When I rename it in the plugin `PHP` file, it affects only the plugin listing.
But it has a separate menu in the left panel. What I need is it to take effect there, so that the user can see the modified name in their user panel. | Here is the plugin directory structure
> yoursite\wp-content\plugins\ [editing-plugin-folder]
open the folder you will find a .php file in there, edit the file using any editor. you can change the name of the plugin in commented area
/*
Plugin Name: Name according to you
Plugin URI:
*/
save the file **refresh** your **wp-admin** **dashboard** and there you go . | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugins, plugin development"
} |
plugin generated 751 characters of unexpected output during activation
I made a custom plugin for my wordpress admin for view user detail. This plugin is working fine after showing this error but the main issue is by this plugin , when i try to open some link the page went blank. I dont know why and what is this error..Searched on internet but unable to resolve this issue. Your help would be appreciated...here is the fulll error comes when i activate this plugin...I
**The plugin generated 751 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin** | Your plugin is causing some errors, but not fatal ones, so plugin works, but as the error messages says, it can cause some problems, i.e. the feed that can output the plugin error so not valid xml content, or when somewhere in the code there is a redirect once _"headers already sent"_ it fail.
If you are asking yourself why the plugin works despite that error, it's because not all errors are _fatal_ (make script die), just as example see following code
if ( ! $number ) {
$number = 1;
}
echo "My number is " . $number;
If you have a code like this in your plugin it will works, but it causes an error because in first line there is a variable that is not defined anywhere.
This is just an example, but there are **a lot** of situations like this where code works but causes errors.
When you develop a plugin, activate **debug and error log** and also I suggest to use some debug tools: some are really useful. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, installation"
} |
Assign default widgets to all sites in a multisite network
I created a widget for sidebar and footer in wordpress multiuser site. I want to make the widgets assigned in MAIN WIDGET AREA and SECONDARY WIDGET AREA by default when new site's created.
Is there anyway to do it ?
I am using wordpress 3.7.1
I tried this method, but didn't works, is it syntax problem calling that function ? | **`wpmu_new_blog`** is the hook you can build your function on.
You will have to find a way to do this.
Sharing a blog which does something else using the same hook when a sub site is created.
`Link to the blog` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, widgets"
} |
get post types and plugin order
I write a simple plugin to get all post types by using get_post_types. But it does not work.
$customPost = get_post_types(array(), 'object');
it returns default post types of wordpress.
When i install Woocommerce plugin, it does not show the custom post types of woocommerce ?
Does it relate to plugin order ? | Post types in WordPress are not _saved_ some where, they are _registered_ everytime you request a page.
So to get all post types, you have to wait untill all post types are registered.
Normally, all post types are registered before the hook `wp_loaded` is fired.
So change your code in something like this:
add_action( 'wp_loaded', 'my_get_all_types' );
function my_get_all_types() {
// if you want only custom post types use '_builtin'=> false in the arguments array
// 2nd argument should be 'objects' not 'object'
$cpts = get_post_types( array( '_builtin'=> false ), 'objects');
var_dump($cpts);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
is_archive() doesn't work on public query var archive pages?
> Public query vars are those available and usable via a direct URL query.
E.g.
example.net/?category_name=tech&tag=gadgets
But doesn't `example.net/?category_name=tech&tag=gadgets` show an **archive**? It definitely uses the `archive.php` template, but for some reason, the `is_archive();` conditional tag doesn't seem to work.
If `is_archive();` isn't the conditional tag to check these archives with, what is? | Try this:
add_action( 'template_redirect', 'my_test_if_archive' );
function my_test_if_archive() {
global $wp_query;
$qv = array_keys( $wp_query->query );
$archives = array('year', 'monthnum', 'day', 'w', 'm', 'author', 'post_type');
$is_archive = ! empty( array_intersect( $qv, $archives ) );
$is_tax = ! empty( $wp_query->tax_query->queries );
if ( $is_archive || $is_tax ) {
// this is an archive
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "query, conditional tags"
} |
Disable the visibility options in WP
Is there a way to disable the public vs private vs password-protected visibility UI when editing or quick-editing a post?
A quick scan in the code yields `#visibility`, which I could hide using jQuery, but I was wondering if there was a documented way to do this "properly". | Quick hack to get the job done, in case anyone else needs to do this:
add_action('add_meta_boxes', function() {
add_action('admin_head', function() {
echo <<<EOS
<style type="text/css">
#visibility {
display: none;
}
</style>
EOS;
});
});
add_action('restrict_manage_posts', function() {
echo <<<EOS
<script type="text/javascript">
jQuery(document).ready(function($) {
$("input[name='keep_private']").parents("div.inline-edit-group:first").hide();
});
</script>
EOS;
});
(Still curious to know if there's a better way.) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "post editor"
} |
Contributors should only access home page
My site's contributors are successfully registered.
However, when they log in I want them to be directed directly to the home page of the site on not to their profile, because they do not need it.
Is this possible?
Thank you. | Yes this is possible. You can use the **login_redirect** filter to do this.
Use the code below in your active theme's **`functions.php`** file.
function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
global $user;
if( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for contributors
if( in_array( "contributor", $user->roles ) ) {
// redirect them to the home page $home_url should contain the home page url
return $home_url;
} else {
return $redirect_to;
}
} else {
return $redirect_to;
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "homepage"
} |
$_SERVER['SERVER_NAME'] in WP_SITEURL
My client has two domains, and wishes to split a product catalogue over them. They want to have a shopping cart that is shared over both, i.e. a shared session over the two domains, this is solved in principle at least, and not the point of this question.
Am using WooCommerce (no choice in this).
Since the products need to available to be ordered in one transaction, they need to be in the same database, so I don't think a normal multisite install is going to work.
I'm hoping therefore to be able to use a single WP install, and simply put `$_SERVER['SERVER_NAME']` in `WP_SITEURL` & `WP_HOME`.
I've seen very few references to doing this, so I'm nervous about possible unforeseen consequences.
Can anyone reassure me, or perhaps tell me why I shouldn't do this? | Personally, I make them default to the HTTP host:
define('WP_HOME', ' . $_SERVER['HTTP_HOST']);
define('WP_SITEURL', ' . $_SERVER['HTTP_HOST']);
There are no caveats for single WP installs. It's in fact very convenient when testing changes in a dev.example.com subdomain, in the sense that it allows to use the same database before rolling out a change on a live site.
Don't do this in multisite installs, however — especially you plan want domain mapping. :-) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
bloginfo() vs get_option?
What's the difference between:
`bloginfo('name');`
vs
`get_option('blogname');`
The parameter is just an example, but I see no differences in terms displaying what I want.
Are there any particular differences? Or are they just for semantic reasons.
Thanks in advance. | The two functions output exactly the same thing.
From the Codex entry for `get_bloginfo()`:
> 'name' - Returns the "Site Title" set in Settings > General. This data is retrieved from the "blogname" record in the wp_options table.
From source:
case 'name':
default:
$output = get_option('blogname');
Neither `get_bloginfo()` nor `bloginfo()` do any sort of sanitization or escaping; so both `get_bloginfo( 'name' )` and `get_option( 'blogname' )` return exactly the same value. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "functions, options, bloginfo"
} |
How to create a category or tag available exclusively to the admins and not to the users?
I would like to create a category or tag name that is available only to the admin(s) and not to the authors.
For example, I would like to create a category or tag called `Exclusive Content`.
Now only admins should be able to add this category or tag to their posts. Other users should not be able to see it or use it.
Is it possible? | Sure, you can restrict access to a tag with the following code:
add_action('save_post', 'remove_tags_function', 10, 2);
function remove_tags_function( $post_id ){
if(!current_user_can('manage_options')){
$post_tags = wp_get_post_terms( $post_id, 'post_tag', array( 'fields'=>'names' ) );
$pos = array_search( 'ExclusiveContent', $post_tags );
if( false !== $pos ) {
unset( $post_tags[$pos] );
wp_set_post_terms ($post_id, $post_tags, 'post_tag');
}
}
}
So, with this code, whenever a normal user adds the tag `ExclusiveContent`, it will be removed upon save _unless_ if the current user can `manage_options`. This code should be added to your functions.php file. You can find this file in your theme's folder. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, tags"
} |
Set colors depending on category
I have this function which outputs the last 6 posts of categories 1 and 2.
<ul>
<?php query_posts('cat=1,2&showposts=6'); ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><strong><?php the_title(); ?></strong></a><br />
<em><?php echo substr(get_the_excerpt(), 0,110); ?> ...</em>
</li>
<br />
<?php endwhile; ?>
</ul>
What I'd like to do is have the link to the article (for instance) red if it's from category 1 and green if it's from category 2. Can you help me? | Setting aside that you're incorrectly using `query_posts()`, the easiest solution is to add a call to `post_class()`, to output post-specific classes, including `.category-{ID}` and `.category-{slug}`:
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<li <?php post_class(); ?>><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><strong><?php the_title(); ?></strong></a><br />
<em><?php echo substr(get_the_excerpt(), 0,110); ?> ...</em>
</li>
<br />
<?php endwhile; ?>
Then, you can use CSS to target `li.category-{ID}`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, wp query, query posts"
} |
What is the best way to mimic a search query within a plugin
I'm in the process of building a Wordpress plugin. I wish to mimic WP's default search functionality but in the form of a 'live search'.
I have my JS setup to grab the query string (i.e what would be `/?s=search-term`) & am passing it via AJAX to my function. But now I have to process the query to get the list of posts & pages. But I've read that it's not right to simply use `query_post` from the WP documentation.
So my question is, **what is the correct approach to yield the same search results as if the default search form was submitted?**
Please can someone provide a code snippet or a link to a detailed article which clarifies this for me.
Thanks & please pardon my nativity! | Pass the 's' parameter to a new `WP_Query` object.
$mys = new WP_Query(
array(
's' => 'whatever',
)
);
That should duplicate the default search. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, search"
} |
Images not rendering
I have a baking blog that I run and recently I have changed the url.
The problem I have now is when I add images to the posts or libary they are not showing/rendering.
The uploading steps go through OK, but the image does not render.
Can you assist, I just don't where I have gone wrong. | Based on the link you posted as a comment to your original question this looks like a permissions issue which could be the result of several things.
Along with the domain change did you change servers too?
First step I think would be ensuring that all of the uploads are readable. `chmod` all files and directories in wp-content/uploads to 755 or 766.
In terminal this would be done by SSH-ing into your server, navigating to the uploads directory `cd wp-content/uploads/` then running `chmod -r 755 *`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
Customizing Comments
Hi I want to customize the text with the arrows pointed at at the image I have uploaded. I have managed to customize some but I cannot find the file to customize the rest.!enter image description here
Many thanks
its on local host, and it is a custom theme. | Presumably you've used `wp_list_comments` to display the comments. That being the case, what you need to do is create a callback function to format your comments and pass that callback into `wp_list_comments` like so:
wp_list_comments(array('callback'=>'mytheme_comment'));
You can use the `comment` method in the `Walker_Comment` class as a starting point. That method provides the default output. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, comments"
} |
2 seperate installation 1 theme same server
i got 2 separate installation on the same folder
each in their own sub folder - they use the same theme
which i copied twice.
Every time i edit a file i need to do it twice and its
a real hassle... How can i define so that they both
use the same theme - a shared theme but a different
database?
I have no "initial code" to share since i don't know
where to begin so an example code would be much appreciated | Three fast and easy options™:
1. Setup revision control (git) for your theme and just pull/push the data around.
2. WordPress Network
3. Create a symlink to your theme folders
Option 1 is the best because it's doesn't matter which theme you edit. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "customization, themes"
} |
Is it possible to work on localhost but have the upload folder linked remotly for dev?
I would like to develop my website locally on my computer WAMP server but the thing is that all images and stuff are on the remote server in the uploads folder. Is there a way to work locally for files and link the upload folder to the remote server for media content ? Maybe a vhost setting or something like that. | Check out Paul Clark's Uploads by Proxy plugin:
> For local development: Automatically load images from the production version of wp-content/uploads if they are missing locally. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "remote"
} |
Looking for a wordpress referral plugin that counts the referral after an action is performed
I am in need of a plugin where, when user A refers user B and user B completes a certain action on the site, he is counted as a referral of user A.I am not looking for a simple "user A refers user B so user B is user As referral" kind of thing.Is there a plugin for that or should I be looking to get an affiliate program for my site?I'm very sorry if a similar question was asked before but I really didn't know how to search for it and get anything relevant :S . | Setup a cookie once a user referred by someone joins your website. Then once someone performs an action, check if he has that cookie and register it as a referral. You can use JavaScript to setup the cookie. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
How to redirect url requests to https?
I've searched far and wide for a solution to this and I am sure it's simple but I simply couldn't find a solution.
This is the regular wordpress redirect code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
How do I make it so that this will always route the url request to `
**Note** : The reason this is posted here and not on any other SO site is that I thought there might be a catch when it comes to WP.
BTW, I put the same question on ServerFault and got a big **On Hold** because "I did not try to solve this myself". | This really belongs on ServerFault, StackOverflow or Webmasters...
But basically, you need to add something along these lines **_before_** the WP rules begin:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ [R=301,L] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "redirect, htaccess, ssl, https"
} |
Breadcrumb how i can display page title with parent > child title with permalink ? any Idea
function the_breadcrumb() {
global $post;
if (!is_home()) {
echo "";
if(is_single()):
echo 'Main';
else:
echo "Home";
endif;
echo " / ";
if ( is_category() || is_single() ) {
the_category(', ');
if ( is_single() ) {
echo " / ";
the_title();
}
} elseif ( is_page() && $post->post_parent ) {
echo "post_parent)."\">".get_the_title($post->post_parent) . "";
echo " / ";
echo the_title();
} elseif (is_page()) {
echo '';
echo the_title();
echo "";
}
}
} | You should change this line:
echo "post_parent)."\">".get_the_title($post->post_parent) . "";
To something like this:
echo '<a href="'. get_permalink($post->post_parent).'">'. apply_filters('the_title', get_the_title($post->post_parent)) .'</a>'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, menus, pages, title, breadcrumb"
} |
Get Posts by IDs (optionally)
I want to check if a variable contains list of post IDs, then I want to query the posts of those IDs only, but if that variable is empty then I want to display all posts.
Problem: If I supply IDs to `post__in`, then it gets the posts with those IDs, but if it is empty then it should return **all posts** but it returns no any post.
For example, the following code will get the posts with IDs 1,2,3. However this will return no any post if the $`ids` is empty. Shouldn't it return ALL posts in that case? How can I get all posts if `$ids` is empty ie. `$ids = "";` ?
$ids = '1,2,3';
$arr = explode("," ,$ids);
$args = array(
'posts_per_page' => $number,
'post__in' => $arr,
); | It looks like WordPress doesn't ignore empty `post__in` param. So you'll have to do this yourself like this...
$ids = '1,2,3';
if ( $ids ) {
$arr = explode("," ,$ids);
$args = array(
'posts_per_page' => $number,
'post__in' => $arr
);
} else {
$args = array(
'posts_per_page' => $number
);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, wp query, loop"
} |
'paged' in wp_query doesn't work
I try to add a code to my wordpress blog show previous posts(in a previous page). I try this code but it don't work:
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
'offset' => 1,
'cat' => -22,
'paged'=>$paged
);
$recent = new WP_Query($args);
while($recent->have_posts()) : $recent->the_post();
// here some code to view
<?php endwhile; ?>
<div class="navigation"><p><?php posts_nav_link('∞','next page','previous page'); ?></p></div>
<?php wp_reset_query(); ?>
it's doesn't work in ` | You set `offset` param, so `paged` param is ignored ;)
From Codex:
> offset (int) - number of post to displace or pass over. Warning: Setting the offset parameter overrides/ignores the paged
If you want to ignore most recent post in this query, you can achieve it in two ways.
**1\. Custom pagination.**
$ppp = get_option('posts_per_page'); // or any other method to get your posts_per_page
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
'offset' => 1 + ( $paged * $ppp ),
'cat' => -22,
'paged'=>$paged
);
**2\. Ignore first post**
$most_recent_post_id = ...; // get the ID of most recent post
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post__not_in' => array($most_recent_post_id),
'cat' => -22,
'paged'=>$paged
); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp query, pagination, paged"
} |
Wordpress Importer Tries to save media files to wrong site folder
I am importing from one WordPress multisite instance to another, using Tools -> Export to generate a WXR file that I then import with and Tools -> Import . I receive the "Failed to import media" message for all files.
When I look at the apache log(on the production server, which is importing) I get:
` [Wed Nov 13 11:05:30 2013] [error] [client 10.11.1.13] client denied by server configuration: /var/vhosts/wordpress/html/wp-content/uploads/sites/10, referer: < `
The path on the test server I am importing from is: /var/vhosts/wordpress-test/html/wp-content/uploads/sites/10
The path to the new site on the production server is: /var/vhosts/wordpress/html/wp-content/uploads/sites/6
I do not understand why it is trying to get to that site on prod | I've created a patch that will work around this issue. This patch is for WordPress 3.6.1. It is a hack, not something that should be taken very seriously except that it points out where the problem may be. I don't know PHP, but was able to trace it back to this point before giving up. I expect someone with more familiarity with the WordPress code base could figure out what the problem is once they see the patch and see what code is being modified.
I did notice that the code is doing a lot of checks against the IP of the remote server. I'm not sure the justification for checking whether the remote server is on a private network, but that may be part of the issue. The server we exported from is on 10.10.2.16, while the server we import on is 10.10.1.206. Both are on the same private network.
The patch is available here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, import"
} |
Is it possible to create an action hook using do_action() within add_action()?
Is it possible to create a new action hook like `do_action('my-hook-name');` inside a call to `add_action();`?
I'm aware this code doesn't work, but I was thinking something along the lines of... `add_action('init', do_action('my-hook-name'));`
or
Is the only way to actually add a callback function to `init`, then inside my callback function create my hook?
add_action('init', 'my_callback');
function my_callback(){
do_action('my-hook-name');
} | Creating an answer based upon responses via comments on original question of: Is it possible to create an action hook using do_action() within add_action()?
Yes it is possible to create an action hook using `do_action()` on a call to `add_action()`.
For clarification, the following code does **NOT** work:
`add_action('init', do_action('my-hook-name'));`
As stated by `@IvanHanák` in the comments to the original question asked; It is possible to create an action hook using `do_action()` on a call to `add_action()` by using anonymous functions.
An example of creating an action hook using `do_action()` on a call to `add_action()` using anonymous functions:
`add_action('some-existing-hook-name', function(){do_action('my-new-hook-name');});`
However, it should be noted that using anonymous functions can make it difficult to debug or remove hooks. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, filters, hooks, actions, callbacks"
} |
CSS file not registering through add_action
Im having a problem to register and load a gallery css code from my home page. Rest of the styles are loading fine, but this flexslider is not registering. Any guidance appreciated.
<?php
function theme_styles() {
wp_enqueue_style ('normalize', get_template_directory_uri() . '/css/normalize.css');
wp_enqueue_style ('grid', get_template_directory_uri() . '/css/grid.css');
wp_enqueue_style ('main', get_template_directory_uri() . '/style.css');
wp_register_style( 'flexslider', get_template_directory_uri() . '/css/flexslider.css' );
if( is_page( 'home' ) ) {
wp_enqueue_style( 'flexslider' );
}
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );
// Enable custom menus
add_theme_support( 'menus' );
?> | The primary issue is an incorrect template conditional tag:
if( is_page( 'home' ) ) {}
This returns true if the current context is a _static page_ , with the slug `home`. I presume that you're _actually_ wanting to test for the **Site Front Page** \- in which case you need to use the `is_front_page()` conditional:
if ( is_front_page() ) {
wp_enqueue_style( 'flexslider' );
}
If the stylesheet still isn't being output, we'll need further debugging information. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "css, wp enqueue style"
} |
Need to build custom metabox select prev posts by category
I am working on a personal project and need the ability to select a previous post based on a selected category. This will be a site devoted to building a pedigree. I really hope this makes sense. I am sitting here trying to think of the best way to describe what I am trying to do.
Any help would be greatly appreciated! | There are surely many other ways to archive something like this but the easiest - in my opinion - would be to create or generate a custom post type and the use of a plugin like Advanced Custom Fields which gives you the possibility to create a metabox with filtered post relations. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, categories, metabox"
} |
Can I use MariaDB instead of MySQL in wordpress?
Is it possible to use MariaDB instead of MySQL in Wordpress installation? If possible: how do I do that? Is there any drawback or complexities? | To answer your exact questions:
* Yes.
* Just use MariaDB instead of MySQL.
* No, it is a straight replacement.
The exact details depend heavily upon your exact situation. However, MariaDB is marketed as a compatible MySQL replacement. AFAIK, it works with WordPress with no changes at all. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "database, mysql"
} |
Custom options for a Custom post type
I have created a custom post type called "Product" with 2 custom fields "Size" and "Color" , I would like the "Size" to be limited to "Small", "Medium" and "Large" , How to I create this list of pre specified values which show up in a Custom Meta box populating an option field ?
Praveen | The easiest solution will be using Advanced Custom Fields plugin, I guess.
You can easily add custom write panels with it and limit them only for some posts based on post type, template file, etc.
If you'd like to do implement it yourself, then you'll have to add your custom meta box using `add_meta_box` function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Custom template pagination
I have a custom post type "news". I created the page "News" with the id 55 and a custom template file. I want to implement pagination.
The problem is when I access the news with a page number set I get an error "404 not found". URL looks like this "/news/page/2/". I use `paginate_links` function to display pagination.
How to display the correct page? | If you've created a **_Custom Post Type_** , then WordPress should be able to handle this for you automagically. Check the Template Hierarchy.
Instead of creating a "Page" and trying to paginate that, create `archive-{post_type}.php` instead. That file will be used as the index file for your CPT, and will show up automatically at `
You've made this too complicated, unless there is a lot of information missing from the question. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "templates, pagination, paginate links"
} |
Display categories inline
how can I show the categories inline in a widget?? I already tried using the wp function wp_list_categories ('style = none') and using the php function str_replace to replace the tags br but without success. Thanks | `wp_list_categories ('style = none')` will `echo` its content as it goes. It won't pass back string that you can replace. You need to use the `wp_list_categories` _filter_ to strip the `<br />` tags.
add_filter(
'wp_list_categories',
function($str) {
return str_replace('<br />','',$str);
}
);
wp_list_categories('style=none'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories"
} |
Wordpress ERD mistake?
I just had a look at the ERD of the Wordpress CMS system and I think I found a mistake... Check the relation between the wp_term_taxonomy and the wp_terms table: <
If I'm correct ONE wp_term_taxonomy (like "brands") can have more wp_terms (like "puma", "nike" etc.) and not otherwise? Cause it says now that one term can have more taxonomies, am I right? | I found the reason:
term_id is the ID of a term in the terms table.
term_taxonomy_id is a unique ID for the term + taxonomy pair.
see: What's the difference between term_id and term_taxonomy_id
Still, I think it's a bit strange to do it this way. Also because I think it doesn´t make sence to not put the taxonomy names in a separate table. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database"
} |
Prevent Indexing of 404 Page
I'm tryying to prevent search engines from indexing my 404 page which is in a template called 404.php. I do not create an actual page, I simply rely on the php template for my 404 errors.
I'm using the code below and it's not working, I'm unsure what the best way to go about this is and I would appreciate help.
<?php if(is_single('404.php')): ?>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW" />
<?php endif; ?> | This won't ever return true:
if ( is_single( '404.php' ) ) {}
The `is_single()` conditional only returns true in a _single blog post_ context. The parameter it accepts is a post ID, slug, or title.
The `404.php` file is a _template file_ , not a _post_. Use `is_404()` instead:
if ( is_404() ) {} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, noindex"
} |
Display articles related to a custom field on a page
I have a little problem to display some articles related to a parent page. I explain.
On the first hand I have a page with a model template. On the wordpress editor part, I create a custom meta field call "cat_page". This meta must be the same as the article related (view more below). This template has a classic loop to display to content of the page :
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
and below I need to display the articles who have the same category name as the page.
if ( get_post_meta($post->ID, "cat_page", true) == the_category() ) : ( have_posts() ) : while ( have_posts() ) : the_post();
It's only what I think it should look, because I have tried several things but I don't know how to proceed.
Image (if it can help)
Thanks in advance. | If I understand well, you have a page template, and you want to use this page template as a category archive.
The term to show is in a page meta field with key 'cat_page'.
If I'm right, in this page template use:
the post(); // being a singular page the 'while' stuff is useless
the_content(); // this will show the page content
$cat = get_post_meta( get_the_ID(), 'cat_page', true ); // get the category to display
if ( $cat ) { // if category is setted in page custom field
$query = new WP_Query( 'category_name=' . $cat ); // run the custom query
while ( $query->have_posts() ) { $query->the_post(); // run the custom loop
// your post loop code goes here
}
wp_reset_postdata(); // reset the post data after the custom query
}
Pleas note that to make this work in the custom meta `'cat_page'` you should put the category **slug** (not the category name). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, page template, post meta"
} |
is it possible open links in new page-window?
I use The List Category Post plugin and i'm very satisfied, but if i would make open the posts (list post) in another page not in the same. Thanks and sorry for my bad english | This was implemented for version 0.36 with the `link_target` attribute:
**link_target** \- Select the `target` attribute for links to posts (target=_blank, _self, _parent, _top, _framename_ ).
Example: `[catlink id=3 link_target=_blank]` will create:
`<a href=" title="Test post" target="_blank">Test post</a>`
Stay tuned for version 0.36 to update. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin list category post"
} |
Term begins with a letter
I had a template that relied on
`$terms = get_terms( "ingredient", array( 'name__like' => $letter ) );`
to return all posts where the custom taxonomy `ingredient` begins with `$letter`.
The behaviour of `name__like` was changed in WP 3.7 to a text search instead of beginning.
What function can I use to achieve the results I had before? Do I need a custom query? | You will need to filter the query, which you can do with the `terms_clauses` hook. This is very similar to G-M's solution but does not require a prefix on your search string.
function old_style_name_like_wpse_123298($clauses) {
remove_filter('term_clauses','old_style_name_like_wpse_123298');
$pattern = '|(name LIKE )\'%(.+%)\'|';
$clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
return $clauses;
}
add_filter('terms_clauses','old_style_name_like_wpse_123298');
// $letter = 'str'; // test
$terms = get_terms( "ingredient", array( 'name__like' => $letter ) ) | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "terms"
} |
How to query post ids liked by the Author
I'm using wti_like plugin and this is how i get the number(count) of post liked by the author
// Get the author object
$author = get_user_by( 'slug', get_query_var( 'author_name' ) );
// Get the post ids liked by the author
$like_ids = $wpdb->get_var("SELECT SUM(value) FROM {$wpdb->prefix}wti_like_post
WHERE user_id = {$author->ID} AND value > 0
GROUP BY post_id ORDER BY SUM(value) DESC");
?>
echo (int)$like_count;
* * *
How can i query the posts liked by the author and use my post format to display them in my author.php template?
ie:
get_header(); ?>
<section id="primary" class="site-content">
<div id="content" role="main"
< ?
$args = array(
//QUERY OPTIONS GOES HERE//
);
$wp_query->query( $args ); ?>
<?php if ( have_posts() ) : ? > | Your query would be something like:
$post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM {$wpdb->prefix}wti_like_post WHERE user_id = {$author->ID}" );
Then you can pass that array of post IDs as the `post__in` argument of `WP_Query`:
$args = array(
'posts_per_page' => -1,
'post__in' => $post_ids
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query posts, query, post meta"
} |
"Theme without sidebar.php is deprecated"
I'm building a custom wordpress theme. When I turn on debug, I get this message:
Notice: Theme without sidebar.php is deprecated since version 3.0 with no alternative available. Please include a sidebar.php template in your theme. in /var/www/wp2/wp-includes/functions.php on line 2968
However, I do have sidebar.php in my theme. It's copied and unedited, from wp-includes/theme-compat
What am I doing wrong? | The call actually comes from `themes compat` like you can read here in source.
So I'd imagine that you simply **copy pasted** the complete contents and therefore just added the `_deprecated_file()` call as well. :D
Lesson to learn from this: Never blindly copy paste stuff without understanding what it does and why it does it. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "theme development, sidebar"
} |
Is there some way to refactor this jQuery wrapper?
I have a script which looks like this
$(function(){
... Jquery Code in Here
});
and I want to wrap it to make it compatible with WordPress. Do I have to do ...
(function($){
$(function(){
... Jquery Code in Here
});
})(this.jQuery);
It works but it seems like there might be a more concise version. Is there? | use "jQuery" instead of "$":
jQuery(document).ready(function(){
jQuery("#mydiv").addClass('myclass'); //or some function here
});
...as found in the codex page. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
} |
How can i limit wordpress post title characters in sidebar?
in wordpress template sidebar and recent posts or recent comments blocks:
when title has more than 30 characters new line created and its not good display
you can see this image for understand what i say:
 no-repeat scroll 8px center rgba(0, 0, 0, 0);
color: #45484A;
display: block;
font: 13px/28px 'OpenSansRegular',Arial,sans-serif;
padding-left: 22px;
text-decoration: none;
}
sidebar style:
#body-right ul li {
background: url("../images/blog-body-right-line.png") no-repeat scroll center bottom rgba(0, 0, 0, 0);
direction: rtl;
height: 28px;
line-height: 28px;
list-style: none outside none;
text-align: right;
}
So how can i solve this problem? | i change body-right css
height:28px; to min-height:28px; and problem solved | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "themes, css"
} |
What is the right way to clean up $title before wp_insert_post?
I am using a function to insert some post data and i am having problems with the title/title - slug. The title is random selected from an array, some title have `?`, `!` or `.` (dots)
I notice `wp_insert_post` doesn't clean up the title so in the title slug (permalink) i see the `?`, `!` or dots. How can i fix this? Any WP built-in function?
This is my function
function my_add_post($title, $content){
// Create post object
$title = str_replace('.','',$title);
$title = str_replace('?','',$title);
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
// Insert the post into the database
wp_insert_post( $my_post );
} | > Any WP built-in function?
Yes, **`sanitize_title`**. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, wp insert post"
} |
One of my posts is displayed as page
I rebuilt a website (I dont know, if the rebuilt has something to do with the problem. It has a whole different database, just the url is the same. the post existed on the old page as well). One of my posts is displayed as a page (I can tell by the class .page).
If I change the permalink from /loriotabend to /loriot-abend it works, but /loriotabend is still available and looks odd.
This is the post, as it should look:
<
This post doesn't even exist in the backend:
<
I would not bother, but Google hasn't indexed the site at the moment, so there is still a link, pointing to /loriotabend. | It seems that < page is an attachment view page. I recommend you just change the name of this < photo to different (in admin panel). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, permalinks, pages"
} |
MS Access to manage WordPress Database
Now I don't believe this is practical or possible without a large amount of development. My client's old site used MS Access to manage the user's profiles on his old website.
His new site uses BuddyPress to manage user profiles, his old site was a bespoke WordPress members system.
I'm just trying to get a concrete answer from someone who knows - is it practical or possible to manage users from MS Access or is it more hassle then it's worth.
Cheers! | If you know something about databases, and have access to the back end SQL database (most likely through Cpanel/phpMyAdmin, you can see the structure of the database, including the columns (fields) and their attributes. Knowing this, you can export an Access query into an Excel file with the same fields and attributes as the BuddyPress SQL table, save the Excel file as a csv file, then import the csv file through phpMyAdmin's import function.
I've done this several times. I don't use BuddyPress, so I don't have the table structure, but you can design all your query exports to Excel to match the SQL structure of the tables in question. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "database, users, buddypress"
} |
Custom Structure permalinks error 404
i have changed the wordpress custom structure permalink to `/%post_id%/%postname%/` and get this error :
**404 Not Found The requested URL /mysite/blog/1/hello-world/ was not found on this server.**
* wordpress version **_3.1.7_**
* site address: **localhost/mysite/blog**
i'v changed this function in **misc.php** and saw the error again!
function got_mod_rewrite() {
//$got_rewrite = apache_mod_loaded('mod_rewrite', true); //old line with false negative;
$got_rewrite = true;//force the response to true as we know mod_rewite is installed;
return apply_filters('got_rewrite', $got_rewrite);
} | Mehdi, it's common problem, as Apache server is not set by this way by default. Your problem can be solved with some very simple steps (simply quoting Samuel B):
> If you want to use permalinks, you will need to make a change inside another file: apache > Conf and find the file `httpd.conf`. Open that in a text editor. Use the search facility in the editor to find "rewrite". The line you need looks like this:
>
> `#LoadModule rewrite_module modules/mod_rewrite.so`
>
> You need to take away the hash sign so it looks like this
>
> `LoadModule rewrite_module modules/mod_rewrite.so`
>
> Now just save the file.
Reference: WordPress Support - Answer by Samuel B
And a warning:
> **REMEMBER:
> NEVER EVER EDIT A CORE WORDPRESS FILE, IT'LL SIMPLY MAKE YOUR WP BUGGY.** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, permalinks"
} |
Installing themes from an external website
**What I am doing**
I am looking for WP theme for an android app. As I couldn't find any searching on WP I looked up on Google and I found that every Theme I found are not available on WP theme search.
An example of this is this webiste
**So, worring on the quality/security of these themes:**
Why are they not available?
Regards, | The answer is **don´t do it if you can avoid it**. You could be installing dangerous code on the server.
Answer based on the analysis done on this blog. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "themes"
} |
content and excerpt not displaying
I am using `get_the_title(453)` and while the title displays, i am unable to display the content and the excerpt for the page with the id of 453. The following is my code
get_the_title(453);
$content = get_the_content();
echo $content;
the_excerpt();
Is there is something i am missing or doing something wrong? | I figured it out myself and it worked. Here is the code if anyone need any help.
$the_query = new WP_Query('page_id=1') ;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_title();
the_content();
the_excerpt();
}
} else {
// no posts found
}
wp_reset_postdata();
* * *
Edit:
This is working because `the_content()` and `the_excerpt()` have to be used within The Loop. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "the content, excerpt"
} |
When localizing a theme do I create the .mo and .po
I'm creating a theme and I want to add internationalization. I have the theme itself set up with the appropriate functions and and textdomain. What I'm curious about is the creation of .pot, .po and .mo files. Most of the tutorials I read involve creating all 3 but twentythirteen/twelve/eleven only include a POT file in the languages directory.
Am I supposed to only create the .pot or am I supposed to make the .po and .mo as well? (note: this theme will not be for myself but one that I will be distributing). | .po and .mo files are created by the translator himself, and then contain the actuall translation, so if you do not supply a translation with your theme then you don't need them.
.pot file is basically a template for the .po file. you can easily generate it with tools like poedit but IMO it is no more then a "nice to have" as part of the theme as any translation tool will be able to generate it from your source. I would say go with the recommendations of the theme repository about the inclusion of the .pot file. If it is not required there, then you can safely omit it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "localization"
} |
Is it possible to check is loaded language files correctly with WordPress plugin?
I have a plugin to be translated. I have done following tasks:
1\. Loaded the TextDomain
$my_td = 'mysignup';
function my_signup_textdomain_init() {
load_plugin_textdomain( $my_td, false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'my_signup_textdomain_init');
2\. Added language files(po, pot, mo) in `wp_plugin_folder\my_signup\languages` (for Bengali bn_BD)
* mysignup.pot
* mysignup.mo
* bn_BD.po
* bn_BD.mo
3\. Changed the language code in `wp_config.php` file
define('WPLANG', 'bn_BD');
But the problem is nothing is changed. I am not sure what I have done wrong.
Now I need to know how can I test everything, whether what I've done is fine, and how can I solve the issue. | I got my mistakes! I done everything good except 1 thing, textdomain setup.
I forgot that i have set the `$my_td` variable outside of function. For this reason, my textdomain was missing. So i made the variable **global** as following:
$my_td = 'mysignup';
function my_signup_textdomain_init() {
global $my_td;
load_plugin_textdomain( $my_td, false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'my_signup_textdomain_init');
Anyway thank for trying to help me.
> **Note: `mysignup-bn_BD.mo` or `mysignup.mo` both will work. But mysignup-bn_BD.mo is dynamic way. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugin development, translation, language"
} |
If metabox has content display content
I know how to display field content if the field has content.
$monday = get_post_meta($post->ID, '_cmb_open_monday', true);
if ( ! empty ( $monday ) ) {
echo 'content';
}
How do I display the content if one of the fields from the metabox "store_openingtimes" has content? Maby this explains better what i want to do:
$storeopen = Get all meta from metabox id "store_openingtimes"
if ( ! empty ( $storeopen ) ) {
echo 'content';
} | You have to list the keys of the meta fields saved in the metabox, because their is no function to dynamically retrieve all the fields saved in specific metabox. For example:
$store_openingtimes_keys = array(
'_cmb_open_monday', '_cmb_open_tuesday', '_cmb_open_wednesday', '_cmb_open_thursday',
'_cmb_open_friday', '_cmb_open_saturday', '_cmb_open_sunday'
);
// all the not empty meta for the post
$meta = array_filter( get_post_custom($post->ID) );
// there are any not empty meta that is one of the store opening times?
$times_meta = array_intersect( array_keys($meta), $store_openingtimes_keys );
if ( ! empty($times_meta) ) { // if so, show content
echo $content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, metabox, post meta"
} |
Add a YouTube or Vimeo video as a post attachment?
I'm developing a gallery plugin and I was wondering if I could add a YouTube and Vimeo "embed" option to the media uploader to be able to add YouTube and Vimeo videos as attachments to a post instead of uploading the video files directly to the server. I'm thinking along the lines of an option with a textarea where one could put the YouTube or Vimeo HTML embed code and this would be added to the media library with a mime type of "text/html".
Any clues would be much appreciated | The OEmbed in Library plugin shows that it can be done. It just lacks a link on the media uploader. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "uploads, attachments, embed, youtube, vimeo"
} |
How to query posts to include specific pages of one post type, and all pages of another post type?
I'm having trouble figuring out how to query all posts from the post type "events", as well as including four specific pages in the loop.
If I use the "include" parameter, it only returns the specified pages. I figure I can use "exclude" to keep out what I don't want, but that's 50+ pages. Is there a more elegant way to do this? | There is not quite any clean way to query for "this set of conditions oh and also something completely unrelated as well".
There are multiple ways to handle it, few of them being:
* query two things and deal with combining in template or around (easy, pain with pagination)
* hook into `WP_Query` and mess with SQL (easy... if you are good with SQL)
* query or otherwise produce combined set of post IDs, then query for that set (can get heavy, but pretty robust overall) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "get posts, include, exclude"
} |
Retrieve posts in custom post type and specific taxonomies
I'm struggling with what seems like should be so simple looking at the codex.
I have a custom post type, let's call it 'portfolio'.
A custom taxonomy for that, let's call it 'clients'.
I can use get_posts() to list all 'portfolio' items but also need the ability to pass in / filter by the 'clients' taxonomy slugs or display all. ("acme,ibm,tbs" - or null/blank)
I've torn apart my sample code so many times that I don't remember anymore what I haven't tried.
Maybe I should instead go with WP_Query()? Sorry for probably such a stupid question, I just can't interpret the example apparently. | Both `get_posts()` and `wp_query()` should be able to do this by passing the `tax_query` array into them.
Example:
$query = array(
'post_type' => 'portfolio',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'clients',
'field' => 'slug',
'terms' => array( 'acme' )
)
),
'orderby' => 'menu_order',
'order' => 'ASC'
);
$posts = get_posts( $query ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, get posts"
} |
get_post_meta() retrieves meta from a specific post on pages, not the page currently viewed
I am making a simple sidebar functionality to display embed video in the sidebar. I've created a meta field where admin should paste the embed video. It works as it should on posts, but on pages, `get_the_ID()` is always returning the same ID, 145, ID of one of the posts.
Here is the code I am using:
<?php
$id = get_the_ID();
$video_value = get_post_meta($id, '_post_video', true);
if (! empty($video_value)) {
echo $video_value;
echo get_the_ID();
} else {
echo 'no video to show';
echo get_the_ID();
}
?>
I am a bit confused, so if anyone could shad some light on this... Thanks! | There is some other query which replaces the main post ID. Might be another widget, some strange plugin code or something else If you have no control over the context, collect the post ID earlier:
add_action( 'template_redirect', 'collect_post_id' );
function collect_post_id()
{
static $id = 0;
if ( 'template_redirect' === current_filter() && is_singular() )
$id = get_the_ID();
return $id;
}
Instead of `get_the_ID()` use `collect_post_id()` now in your code.
$video_value = get_post_meta( collect_post_id(), '_post_video', true ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom field, pages"
} |
enqueue script only if it is not already enqueue
I want to include a script in a shortcode output, so I am trying this:
function my_shortcode( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
), $atts));
wp_enqueue_script('custom-script');
}
I have registered the script already and enqueue it if the above shortcode is used. However I want to include the file only once, even if the shortcode is used multiple times. Currently, if the shortcode is used multiple times, it will include the script for each time. Is it possible? | The WordPress enqueue system should prevent the inclusion of the same script multiple times, and does when I test it. For example, the following enqueues a Core script and `echo`s a counter. If I put this shortcode into a post 4 times, I get "0123" but the media script only loads one time. The same test works with several other scripts I tried.
function my_shortcode( $atts, $content = null ) {
extract(shortcode_atts(array(
'title' => '',
), $atts));
static $counter = 0;
echo $counter++;
wp_enqueue_script('wp-mediaelement');
}
add_shortcode('enq','my_shortcode');
If you are getting the same script loaded over and over, there is a problem with your site, but I am not sure where start guessing at what. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 4,
"tags": "plugins, plugin development, shortcode, wp enqueue script"
} |
How can I target WordPress 3.8 new interface MP6 with CSS?
When MP6 was a plugin in WordPress 3.6+ it changes the body class of the admin and added an "admin-mp6" class which helps me to style my plugin accordingly.
Now with the latest Alpha of WordPress 3.8 the class was removed. I know since it's an alpha version the class may come back but I wonder if there are any official "best practices" | Andrew Nacin posted some "offical" approach to this topic here
The CSS only variant should use the branch-3-x class to target the versions **before** 3.8 and the defaults should get applied to all upcoming versions so you don't have to care about further version:
.branch-3-6 .some-selector,
.branch-3-7 .some-selector {
/* some rules go here for 3.6 and 3.7 */
}
.some-selector {
/* 3.8+ rules go here */
}
Read more about this topic on the make.wordpress.org page | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 7,
"tags": "admin, css"
} |
How can I format email notification after registration?
I saw already this answer. And it helped me to make unique mail. It's great. But how to format some text using HTML? For example to work with tags
<b> <i> <font color="red"> <img src="">
I wrote
spintf("<a href="
And on my mail I got letter with `<a href=" instead of this Text. It seems that WordPress mailer cut HTML, cause I tried printf and echo. Or may be I just do something wrong? | wp_mail from Codex
Use this example:
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
wp_mail( $mails_to, 'The subject', '<p>The <em>HTML</em> message</p>' );
// Reset content-type to avoid conflicts --
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
function set_html_content_type() {
return 'text/html';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "notifications, wp mail, phpmailer"
} |
If Parent or Current Page Is, Then Statement?
I need a conditional statement which checks to see if the page the user is currently on is a child of a specific parent page or that parent page itself, and if so, display a link. How do I achieve this in WP? | Use get_post_ancestors():
// get page ancestors
$parents = get_post_ancestors( $post->ID );
// id of parent page you want to find
$parent_id = 123;
// check of $parent_id
if ( $post->ID == $parent_id || in_array( $parent_id, $parents ) ) {
echo '<a href="#">Link</a>';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "conditional tags"
} |
Filter Orders in Admin area, based on Custom meta
**Story:**
I have custom role `Staff` for my WooCommerce shop,
When a Customer create an Order, the Order is assigned a custom meta name `handle_by` where the value is a random value of user where role is Staff.
When Staff is login and click `WooCoomerce > Orders`, He/She will only see Orders where `handle_by` is match current user id.
**Problem:**
How to filter WooCommerce > Order to only show Order where the custom meta `handle_by` is match with current user login. | Solved it, using `pre_get_posts` filter and `WP_Query->set()` method
function foo_filter_orders($query) {
global $pagenow;
$qv = &$query->query_vars;
$currentUserRoles = wp_get_current_user()->roles;
if (in_array('shop_manager', $currentUserRoles)) {
if ( $pagenow == 'edit.php' &&
isset($qv['post_type']) && $qv['post_type'] == 'shop_order' ) {
$query->set('meta_key', 'handle_by');
$query->set('meta_value', 'shopmanager1');
}
}
return $query;
}
add_filter('pre_get_posts', 'foo_filter_orders'); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "plugins"
} |
How do I change the default admin color scheme in MP6
How do I set a different default admin color scheme for all users?
For example, it's set to MP6 as default now, but I want to make it MP6 light by default.
The users may or may not change it later!
What I've learnt so far is that it could be done by hooking into `get_user_option_admin_color`
Here's the code from the plugin author:
<?php
add_filter( 'get_user_option_admin_color', function( $color_scheme ) {
global $_wp_admin_css_colors;
if ( ! isset( $_wp_admin_css_colors[ $color_scheme ] ) ) {
$color_scheme = 'ectoplasm';
}
return $color_scheme;
}, 5 );
But as a non-savvy I couldn't figure out where to put this code to make it work.
Can anyone help me? | If you are using a hook to add/edit a function. Add the piece of code in the active theme's **`functions.php`** file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "customization, wp admin"
} |
"Template is missing" install error on non-child theme
I understand the first comment in `style.css` dictates the difference between original theme and child theme.
Using the following simplest example is throwing the "Themes must have a stylesheet and a template ... Template is missing" error:
/*
Theme Name: Test
Theme URI:
Description: Test install
Author: Test
Version: 1.0
Tags: Test
*/
File structure inside of `themes` directory:
themes
-twentythirteen
-test
-css
-style.css
-index.php
The css seems to parse correctly and has line breaks making each entry in the comment distinct. I've tried creating multiple themes, all with the same result. The default themes are loading fine. Running this locally using MAMP, wp version 3.7.1.
Pulling my hair out here... any suggestions? | Move `style.css` out of `/css` and into the Theme's root folder. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, local installation"
} |
Post order by selected tags
Let's say you want to show posts tagged with tags : "HTML, CSS".
I want to order posts in tag archive in the following order:
Post tagged with only exact two tags - HTML,CSS
Post tagged with only exact two tags - HTML, CSS
Posts tagged with three tags - HTML, CSS, jQuery
Posts tagged with three tags - HTML, CSS, ZEND
Posts tagged with four tags - HTML, CSS, JavaScript, PHP
etc.
So first result/s should only output posts with only exact specified tags. After there are no more posts tagged with only those two tags, output posts tagged those 2 tags + only one more tag. And so on.
What should I use? Two wpQueryPosts loops? Can it be done with only one loop? How to sort by matched tags? | You can count the number of tags when a post is saved and store it as a meta key for the post. Now you can just add a sort by the value of the meta key to the tag page query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags, order"
} |
How to update scrollbar when using Jetpack's Inifnite Scroller?
for the last couple of days, I have been trying to have a custom scrollbar (jquery+css) while using Jetpack's infinite scroller.
What I want is to get rid off the standard scrollbar and use a custom one for my content. I have tried a couple and most of them have an update function that I need to insert somewhere into Jetpack's Infinite scroller (js) so when it loads the content, the custom scrollbar gets updated and it resizes itself.
The problem is that I have no idea where to insert this update function. Can someone please help me?
I wont post any code because they are all pretty much the same. Anyways, if for some reason, you do need to see it, you can check out this one at: < | Ok, I found the solution at Jetpack's website, <
I just needed to insert the custom scrollbar's update function inside this function provided by jetpack's infinite scroll.
" **JavaScript Events**
Inevitably, there are situations in a theme that require some JavaScript interaction after posts are added. One such example is in a theme that uses jQuery Masonry and needs to trigger that library to position the additional posts. Recognizing this need, we trigger an event after posts are appended. To make use of this event, simply catch the post-load event when it fires on document.body:"
( function( $ ) {
$( document.body ).on( 'post-load', function () {
// New posts have been added to the page.
} );
} )( jQuery ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, css"
} |
wordpress str_replace the content with tag
it is possible to find tag in the content and replace with link?
function replace_content($content){
foreach(get_the_tags() as $tag) {
$out .= $tag->name .',';
$csv_tags .= '"<a href="/' . $tag->slug . '">' . $tag->name . '</a>"';
}
$find = array($out);
$replace = array($csv_tags);
$content = str_replace($find, $replace, $content);
return $content;
}
add_filter('the_content', 'replace_content'); | I can see that you are constructing an array with only **one** element, something like this:
array( 'green, yellow, red' )
instead of an array with multiple elements:
array( 'green', 'yellow', 'red' )
Try to replace these lines:
$out .= $tag->name .',';
$csv_tags .= '"<a href="/' . $tag->slug . '">' . $tag->name . '</a>"';
with
$find[] = $tag->name;
$replace[] = '<a href="/' . $tag->slug . '">' . $tag->name . '</a>';
and remember to declare the arrays at the top:
$find = array();
$replace = array(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "tags"
} |
Cannot redeclare wp_update_core()
I think it's right after the WordPress update, we can't access the wp-admin to log in anymore.
> **Fatal error:** Cannot redeclare `wp_update_core()` (previously declared in C:\DWASFiles\Sites\pyromaitre\VirtualDirectory0\site\wwwroot\wp-admin\includes\update.php:288) in C:\DWASFiles\Sites\pyromaitre\VirtualDirectory0\site\wwwroot\wp-admin\includes\deprecated.php on line 1076
What cause this? How can I resolve it? | you probably need to reinstall manually the wordpress core with the help of FTP software
1. download from wordpress.org the latest version of wordpress.
2. rename or delete the wp-admin and wp-oncludes directories
3. upload wordpress.
to be fully safe during this process you might want to add a .maintenance file before step 2 and remove it after step 3. this will put your site into maintenance mode for the duration of this operation. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, core"
} |
Prevent Title Edit In post.php
I am looking for a way to disable the editing of a post's title when on post.php.
I want the title of a post to remain "fixed", but editing of the content to be possible.
function my_remove_meta_boxes() {
if( !current_user_can('delete_published_posts') ) {
remove_meta_box('titlediv', 'post', 'normal');
}
}
add_action( 'admin_menu', 'my_remove_meta_boxes' );`
This will completely remove the title box, which somewhat achieves the goal, but I would ideally like to still be able to actually display the Title - just that it can't be edited | You can use a simple jQuery code to disable the title field.
jQuery(document).ready(function() {
poststatus = /* get this from your php code */
if( poststatus != "auto-draft" ) {
jQuery( "#title" ).attr( 'disabled', true );
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts"
} |
Custom Post Type Root Template
I've created a custom post type for this project I'm working on. I've defined the URL slug to be 'vendors'.
So now when I browse to www.mysite.com/vendors, it shows all of my Custom Post Type posts.
I don't want the root slug to be a listing of all my posts.
Is there a way to have a custom template defined for the /vendors/ slug? | There are a couple of solutions:
1. Create `archive-vendors.php`, that displays whatever output you want (including static content or a secondary query, for example), and omitting the default loop (CPT archive index query).
2. Set `has_archive` to `false` in your `register_post_type()` call, then create a _static page_ named **Vendors** , that you can use to display whatever content you want (including via a custom page template). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Give Editor Access to Custom Theme Options
I have a theme-options.php file and am trying to grant Editor users access to edit it.
I've managed to give them access to the page itself by modifying the parameters in this function to include 'moderate_comments':
function theme_options_add_page() {
add_theme_page( __( 'Theme Options', 'sampletheme' ), __( 'Theme Options', 'sampletheme' ), 'moderate_comments', 'theme_options', 'theme_options_do_page' );
}
However, when I try to edit / save the options, I get given a message saying:
> Cheatin’ uh?
Can anyone see what the issue is?
Here is the code for my options file if that helps! \- < | The problem is that the default Editor role does not have enough capabilities to change theme options. You are allowing users with 'moderate_comments' capabilities to view the page. That in itself is not enough. When the user attempts to update, it fails because the user does not have the proper capabilities, hence the 'Cheatin’ uh?' message. I believe you need to give Editors 'manage_options' capabilities and possibly others. You can achieve this using various WP plugins that can change role or user capabilities. Here is one that I have used - <
Your function to add the option menu page should only be viewable to users with 'manage_options' capability
function theme_options_add_page() {
add_theme_page( __( 'Theme Options', 'sampletheme' ), __( 'Theme Options', 'sampletheme' ), 'manage_options', 'theme_options', 'theme_options_do_page' );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "user roles, theme options, editor"
} |
Change type of permalinks on TinyMCE link dialogue
I recently ran into a problem when inserting text links into post content, and then updating the target post's slug or changing permalink options - the link in the post content won't get updated.
This is only really an issue if you forget where you've put text links to other posts, and so don't update them.
So I hit on the idea of somehow altering the Link dialogue in TinyMCE to use shortlinks instread of inserting the full permalink:
so `example.com/mypage/somepage` would instead be inserted as `example.com?p=123`
This way the content links wouldn't need updating unless you trashed the target post. Does anyone have an idea on how to acheive this - I was hoping there would be a filter for the page results in the link dialogue? | This is not a real problem as wordpress remembers all the addresses the content had during it existence and automatically redirects to the recent one. The code is not 100% fail prof but you will need to work very hard to make it fail.
That is the reason you don't need to update links in your content when you change the permalink structure or the slug. If the redirects bother you then use one of the plugins that can detect that (I use broken links) or an external utility. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, tinymce"
} |
Internal and External Blog
My company is looking to start an internal company blog that only our employees have access to. We are looking at Sharepoint and other options to do this, one of which is WordPress. (Not everyone in our office has Sharepoint, but my questions on that will be going elsewhere.)
There is the possibility that we will also want an external, public blog at some point.
Can we have both a private company blog and a public blog with WordPress?
And if anyone has enough knowledge to compare, what would the pros and cons be for Sharepoint vs WordPress?
Thanks for your time and help! | > Can we have both a private company blog and a public blog with WordPress?
Yes, but it depends on how you define private. We use WP multisite subdomains. We have over 200 sites, most of them public. But we have a few sites that are "private" - requires user to login. Additionally the user has to have been registered with the site.
You can achieve this using a plugin. We wrote our own but there are many out there, for example - < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "blog"
} |
Category base 404 - fix
I have seen the problem before when hacking in WordPress
When trying to access the
**www.example.com/category/**
I get a 404-page displayed.
Is there a way to display something useful such as a page with custom code instead of the 404-page?
Need your help to figure this out, please tell me if something is unclear. I tried to add the tags category-base and category-page but that did not work. I you have suggestions on good tags please inform me. Thanks Anthony | Yes, there is such way. To be precise, there are many ways to accomplish that.
You can **add 'Category' page**. Make sure that its slug is set to 'category'. If you go to example.com/category/ then this page will be shown. If there were no custom changes to rewrite rules, then WordPress will first try to match pages, and then categories, so it should work.
You can also **remove category base from url**. You can do this using some plugins (WP No Category Base - WPML compatible is one of plugins you could use). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, theme development, taxonomy"
} |
How to hide title on 'highlights' - Themify feature
I am using Themify's Flat theme and in the Highlights I want to hide the title of my highlights. Any ideas on how to do this?
Thanks in advance. | I am not familiar with the theme, but assuming the title's class is title put this into your css file: `.title { display: none; }`. If it is an id put this in there `#title { display: none; }`. And if it is an html element like h1 use this `h1 { display: none; }`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, title"
} |
Publish a Silent Post without updating Feed
Is there a way to publish certain posts, silently without updating the feeds and those posts also should not appear in the home page.
Appreciate your help. | A simple ways to do it, publish it with a past date. If you need to post content that should not behave like normal posts then you should consider posting it as a page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, feed, publish, feedburner"
} |
Add custom directory in URL
How can i add custom "directory" in my URL for pages and posts?
So the main website url is: ` but when i go to a page I want this kind of URL: `
How can I put that "SOMETHING" in URL without affecting Wordpress functions? | Go to your
`Dashboard => Settings => Permalinks`
click on `Custom Structure` and paste this `/something/%postname%/`
And you can replace `something`
It will add the `something` keyword before pages and post url slugs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "permalinks, url rewriting"
} |
Non-Recursive get_term_children()
I have a custom taxonomy called `product_category`. There are child terms 3 levels down.
They look like this:
Term1
Term2
Term3
When I am on the taxonomy page for Term1, I wish to use `get_term_children()` to retrieve Term2, without retrieving Term3.
If that makes sense...
Can this be achieved with get_term_children() or is there another function I can use? | Presumably you want to output term data, so you can use `get_terms` with the `child_of` argument, then iterate over returned terms and check that the parent of each term is your main term id:
$parent_id = 42;
$children = get_terms( 'product_category', array( 'child_of' => $parent_id ) );
foreach( $children as $child ) {
if( $parent_id == $child->parent )
echo $child->name;
}
This will exclude grandchildren, as their parent term ID will be a child term, not your top level term. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, terms"
} |
Custom Post Types. Are there any disadvantages/advantages in using a plugin to develop them?
There are a few plugins which can assist you in building your CPT's, and these can usually handle your taxonomies and sometimes postmeta also. Some even take it further than that. I know that as with any plugin it's possible that development may cease; but aside from that are there any reasons why it's better to code your own CPT's taxonomies etc.
**Here are some of the plugins I'm referring to**
* Custom Post Type UI
* Types
* WCK
* Custom Post Type Maker
**Here's my Advantage/Disadvantage list**
_Advantages_
* Quicker and Easier
* Developers have hopefully considered security so no need to worry about nonces or protecting the database etc
_Disadvantages_
* Might be a performance issue for some applications
* Depending on development to continue.
* Possibly Less Flexible
Does anyone want to add to or take away from this list? | I think there's no really huge difference, you choose the tool that you feel most comfortable yourself. Plugins have the drawbacks you mentioned, and doing them from scratch can be a bit slow and tedious.
The 3rd alternative, that I find really good, is a PHP class that does all the heavy lifting for you, but is still light and easy to use, e.g. Easy-WordPress-Custom-Post-Types. This particular class does custom taxonomies and metaboxes also. Very handy. So you'll eliminate bunch of plugins with one hit. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, plugins, post meta, performance"
} |
WP Query get posts by specific author IDs if one of several logged in authors
I have a custom template page where posts are shown from authors 1,2 and 3.
<?php $the_query = new WP_Query( 'posts_per_page=-5&author=1,2,3' ); ?>
How can I use **get current user** in this so that the posts are only visible to an author with one of those ID's (1,2 or 3) and are logged in?
In other words: Author 4 will not see any posts. Authors 1,2,3 will see each others posts if they are currently logged in.
Thanks very much in advance- | If I'm understanding this correctly something along these lines should work.
$authors = array( 1, 2, 3 ); // privileged users array
$signed_in_user = wp_get_current_user(); // get current user
// check if singed in user is in authors array
if ( in_array( $signed_in_user->ID, $authors ) ) {
$query = array(
'posts_per_page' = -1,
'author__in' = $authors
);
}
else {
// alternate query for other users
}
$posts = new WP_Query( $query ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, author"
} |
Get an uploaded attachments local server path?
All the wordpress functions for retrieving media details seem to give you the web url of a file uploaded. I want to the local server drive/folder path, ideally relative to the install of wordpress. I have the attachment id value to hand so can parse that to a function, if only I knew what it was.
Is this possible with a function built in that I've missed? If not does anyone have anything pre-written for this function? | `get_attached_file` returns the server path of an attachment. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "uploads"
} |
Fatal error Call to a member function insert() on a non-object
I am running Custom Query on `functions.php`:
function subscribers(){
if(isset($_POST["email"])){
$email = $_POST["email"];
echo $wpdb->insert($wpdb->easymail_subscribers, array('email' => $email));
}
}
add_action('wp_ajax_subscribers', 'subscribers');
add_action('wp_ajax_nopriv_subscribers', 'subscribers');
This is being call by AJAX request. I got this error message:
> **Fatal error** : Call to a member function insert() on a non-object in **G:\xampp\htdocs\Projects\newsite\wp-content\themes\generic\functions.php** on line **235**
>
Tried really hard to solve this, but was not possible. | You need to make sure you are using the global $wpdb
function subscribers(){
global $wpdb;
if(isset($_POST["email"])){
$email = $_POST["email"];
echo $wpdb->insert($wpdb->easymail_subscribers, array('email' => $email));
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, query"
} |
Custom headers in WordPress, are there also custom footers?
I’m new to WordPress. I saw a custom header file in the `inc` folder of Twenty Twelve theme. I understand that we can use this custom header in any custom page template instead of header.
I have a doubt now, is there any custom footer that also can be used? Why this custom files should be stored in `inc` folder? | You can take a look at Custom Headers documentation for information about it.
There is no "custom footer" feature, well because WP only has "custom header" theme feature and it isn't named/scoped to handle arbitrary custom-something.
> why this custom files should store in "inc" folder?
This is just an implementation detail of specific theme, it's not required or standardized in WordPress. `inc` is short for `includes` and is typical name for folder containing PHP files (other common folder names being `php` and `src`). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers, footer, custom header"
} |
Vagrantpress + composer
I was looking at the roots.io blog, where I learned about Vagrant and Composer which in combination seem to give you a more intelligent development environment and dependency management system. I choose to get and install Vagrantpress since it seems like the easiest way to get started with wordpress + vagrant. The plus of Vagrantpress is that it installs Wordpress and all its dependencies for you. As I understand Composer in adjunction with Wordpress, is that the easiest way to combine the two is to use the Outlandishs WordPress Packagist. Now my question is, how are people using Composer and Vagrantpress tougher? How does your setup look like? Are there any good examples of composer.json file + Vagrantfile for Vagrantpress?
/PS: If someone with enough rep could create the Vagrant and composer tags that would be great. No relevant tags really exist, but I hope the question is relevant enough. | Unfortunately you can't use Vagrantpress and Composer directly together easily. Half of Vagrantpress is the WordPress setup itself which isn't compatible. If you still wanted to leverage the base work Vagrantpress has done with PHP, Apache, MySQL etc, you could fork it and modify their WP module found here: <
It would still require a decent amount of changes though since you'd need to install Composer, modify their wp-config.php (the ones outlined in the Roots blog post), and run `composer install` instead of downloading the WP tar.gz.
It might just be easier to built a custom LAMP style Vagrant file with < and then write your own manifests for the WP/Composer part. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, json, linux"
} |
Undefined index: id, when I save the options
I'm making a Wordpress theme and I get these 'Notices' repeated a lot of times when I save the options using the WP_DEBUG:
Notice: Undefined index: id in /var/www/Seozeta/wp-content/themes/seozeta/seozeta-options.php on line 997
Notice: Undefined index: id in /var/www/Seozeta/wp-content/themes/seozeta/seozeta-options.php on line 1000
The code is this:
foreach ($options as $value) {
if (isset($_REQUEST[ $value['id'] ] ) ) { //#997
update_option( $value['id'], $_REQUEST[ $value['id'] ] );
} else {
delete_option( $value['id'] ); //#1000
}
}
It seems the initial **isset** should work and fix the problem, but it is not. I numbered the lines affected using the comments in PHP.
What am I doing wrong? Any suggestions? | Add `var_dump($value);` at the beggining of this loop. I'm pretty sure that not all options have `id` property and it may be some other bug...
To get rid of these notices, your code should look like so:
foreach ($options as $value) {
if ( array_key_exists('id', $value) ) {
if (isset($_REQUEST[ $value['id'] ] ) ) { //#997
update_option( $value['id'], $_REQUEST[ $value['id'] ] );
} else {
delete_option( $value['id'] ); //#1000
}
}
}
_PS. This notice has nothing to do with WordPress, so it's off-topic._
_PPS. Some time ago I've shown you how to debug such problems, have you even tried to solve it by yourself?_ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp debug"
} |
Custom filter for main search: how to exclude specific post_type from search results
Is there a way to use WP_Query's method, set(), in order to exclude a specific post_type from a global search.
Here was my unsuccessful attempt:
function _search_all($query) {
if($query->is_search()) {
// get rid of in the news
$query->set('post_type__not_in', array(IN_THE_NEWS_SLUG));
if(isset($_GET['post_type'])) {
$query->set('post_type', $_GET['post_type']);
} /*else {
$query->set("post_type", array(FEATURES_ID, BRIEFS_ID, PRESS_RELEASES_ID));
}*/
}
return $query;
}
add_filter("pre_get_posts", "_search_all"); | You can define the exclusion of `post_type` while registering for the post.
Use the below param to make this work
**`exclude_from_search => 'true'`**
For more details check the **codex** | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, wp query, search, post type"
} |
Why is get_pages() returning a boolean?
I have created a custom post type that I want to use to allow people to add an arbitrary number of sections to the homepage of my theme. I want to loop through all posts of that type and include their contents in the page. My problem is that calling `get_pages()` with `'post_type' => 'home_section'` seems to be returning a boolean, not an array.
Here is the code I'm using to test:
<?php
$hp_sections = get_pages(array('post_type' => 'home_section'));
echo '<!-- $hp_sections type: ', gettype($hp_sections), ', value: ', $hp_sections, ' -->';
?>
When I view source on my page I get:
<!-- $hp_sections type: boolean, value: -->
I'm pretty new to both PHP and Wordpress so I'm assuming I'm making some sort of dumb mistake. I'd like to know both what is wrong with the above code and what the recommended way to get all pages of a given type and iterate over them inside a template is. | Historically I've had better luck using `get_posts()` over `get_pages()`. Especially in the case of a custom post type, I'd recommend using something like
$args = array(
'post_type' => 'home_section',
);
$hp_sections = get_posts( $args );
instead of using `get_pages()`.
### Reference
* `get_posts()` on the Codex | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom post types, pages"
} |
Videos via the video shortcode are always 640px wide?
I've run into a particular problem with the Video Shorcode of WP.
I can't seem to change the size of the player with the attributes of the Shortcode.
This happens on multiple sites with multiple templates (Twenty Thirteen included).
Here's the visual :
!enter image description here
So I have 2 video tags, one with a width of 720 and the other with a width of 930.
!enter image description here
In the page, they are both the same size (640px wide) even if they still have place in their container (see orange box by the developper tools, meaning that there's untaken space on the right of the first video) and they both had different sizes over 640.
I don't understand what is happening here. Do I give wrong arguments to the shortcode? I tried to give the width in pixels (720px) but had the same problem. | That width is dictated by the `$content_width` global, defined by the Theme. To change it, you'll need to hook into `after_setup_theme` and modify it:
function wpse124075_setup_theme() {
global $content_width;
if ( ! isset( $content_width ) ) {
$content_width = 640; // your value here, in pixels
}
}
add_action( 'after_setup_theme', 'wpse124075_setup_theme' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "shortcode, videos, video player"
} |
woocommerce product attributes
Forgive me if someone has asked this before, but i am trying to get some attributes displayed next to displayed content of product. I see the hook `woocommerce_before_single_product_summary` that displayed few attributes but not all. The `woocommerce_before_single_product_summary` let me back to directory structure in woo/templates/single-products/filename which is just
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
if ($product->is_on_sale()) :
apply_filters('woocommerce_sale_flash', '<span class="onsale">'.__( 'Sale!', 'woocommerce' ).'</span>', $post, $product); ?>
endif;
Now i am lost, where do i go from here? How do i add my attributes to my product-catalog and single product page? Where do i go from the `apply_filters`? How do i find the generated html for the attributes? | A look at the documentation or the source is always helpful. I guess, the correct file to refer to would have been `product-attributes.php`. For getting the product attributes this is available: `get_attribute()` ; to list them `list_attributes()` can be used, which makes use of the `product-attributes.php` template. You can use those and then hook into the fitting one to display the attributes. To learn more about hooks give the Plugin API a good thorough read. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, hooks"
} |
site-description css is overriden
I'm trying to change the site-description color of my twentythirteen header to #220E10.
My style.css file reads :
.site-description {
font: 300 italic 20px "Source Sans Pro", Helvetica, sans-serif;
color: #220E10;
text-align: center;
margin: 0;
padding-bottom: 25px;
}
However, the color of my header (viewable here) remains #FF6000.
I know the css file is the used as a source for size, font and other details, since I can effectively change those and see the results happen. The color will not change however.
I suspect the override has something to do with the basic Wordpress editor which allows you to change the color of your header text.
I can't seem to be able to identify the location of the source css being used for this color. The #FF6000 color is not present in my style.css file, except for that intentional navbar.
Could you help me edit the site-description to a different color ? | There's a CSS rule being output in the `<head>` of that document that is defining the color, _after_ your stylesheet is included (thus overriding it). Take a look at the options for the theme, and see if there's a way to set the color through the admin area.
If you want to override JUST the description, add `!important` to the color rule in your css file. It's an unfortunate solution, since `!important` rules can cause all kinds of havoc during maintenance phases... but the other option is to dig into the theme files and try to change the options settings to two color settings, or change the output in the theme header so it only defines a color for the title, instead of both the title and description. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "css, headers, theme twenty thirteen"
} |
How can Custom Post Type and a page have the same slug?
I have a page called "Art" that can be viewed at `/art`. I also have a custom post type called "samples" with a post called "Art" inside of it. It SHOULD be viewed at `/samples/art`. For some reason, instead of having `/samples/art` as the URL, WordPress is forcing `/samples/art-2`.
The Art page and the Art post are two completely irrelevant pieces of data. Is there any way to let both of these entities exist with a clean URL? | This is a known bug (or design flaw) that seems be getting some attention by the Wordpress team. Take a look at this discussion < for more information. As of Wordpress 4.0 this is still an issue. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, slug"
} |
Author Page List - change to show authors instead of not subscribers
I am trying to change this code in my Authors List page template
$all_users = get_users();
$allowed_users = array();
foreach ( $all_users as $user ):
$wp_user = new WP_User($user->ID);
if ( !in_array( 'subscriber', $wp_user->roles ) ):
array_push($allowed_users, $user);
endif;
endforeach;
to show only authors instead of "everyone except subscribers". I tried this:
if ( in_array( 'author', $wp_user->roles ) ):
and it does not work.
How can I change this code to show only users defined as 'author'? | `get_users` has an argument that should let you select a particular role.
$all_users = get_users(array('role'=>'author'));
Should be all you need. `$all_users` should be only "Authors". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author"
} |
How to remove admin bar logo in WordPress using plugin
I'm following the instructions from this page to remove the adminbar wordpress logo and cannot quite understand why this is not working in a plugin I have created.
// Hide top left WordPress logo
add_action( 'admin_bar_menu', 'remove_wp_logo', 999 );
function remove_wp_logo( $wp_admin_bar ) {
$wp_admin_bar->remove_node( 'wp-logo' );
}
Everything else in my plugin is working except this. Only difference I see in that example is that it is referring to the functions.php file?
Any thoughts would be appreciated? | This one does the job for us, we use WP3.7.1.
function no_wp_logo_admin_bar_remove() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('wp-logo');
}
add_action('wp_before_admin_bar_render', 'no_wp_logo_admin_bar_remove', 0); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "admin bar, logo"
} |
How do I add a text field under the activity texarea?
I am working with BuddyPress 1.7. I need to add a text field under under the activity/update text area and capture that data when an update is posted. Any help to help to get me started would be much appreciated.
I see the `post-form.php` file that contains the HTML form elements but how can my text box be added using a plugin through a filter? | I was able to add text field under the activity text area using the `bp_after_activity_post_form` hook.
add_action ( "bp_after_activity_post_form", 'test' );
function test()
{
echo '<div id="tags-content">
<input type="text" name="tags" value="" />
</div>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, buddypress"
} |
Woocommerce Attributes pulling in wrong data
My Problem is very strange - I don't fully understand all the aspects of woocommerce just yet and am still fiddling with things to understand it.
I'm trying to pull in the size attributes for each product - I'm succeeding in pulling in the attributes but I'm pulling in all of them for every product. Not the one's I'm adding to the product via the custom field.
Example of the attributes that should be pulled in link
But I'm pulling all 6 of my created attributes not the one's selected for each product. link
The code I'm using to pull in the attributes is the following
<?php
$terms = get_terms('pa_size');
foreach ( $terms as $term ) {
echo "<li>" .$term->name. "</li>";
}
?> | You are confusing `get_terms()` with `get_the_terms()`
`get_terms()` returns an array all the terms in a taxonomy.
`get_the_terms()` returns an array of all the terms for a particular post.
global $post;
$terms = get_the_terms( $post->ID, 'pa_size');
foreach ( $terms as $term ) {
echo "<li>" .$term->name. "</li>";
}
You might also like `get_the_term_list()` which would be like so:
global $post;
echo '<ul>';
echo get_the_term_list( $post->ID, 'pa_size', '<li>', ',</li><li>', '</li>' );
echo '</ul>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, plugins, php"
} |
Determine Term depth
I'm looking to be able to find the depth of a term within it's hierarchical tree.
Produce
-- Vegetables
---- Carrot
---- Onion
---- Celery
-- Fruit
---- Apple
------ HoneyCrisp
----Orange
Produce is level 0 (or 1), Fruit is level 1, Apple is 2, HoneyCrisp is 3, etc.
Ideal usage is `$depth = get_term_depth( $term_id );`. Anyone have experience with this?
I essentially want a different rendering depending on depth on a term archive page. | Not trying to bump my rep, but I found my own answer. `get_ancestors` allows you to get the hierarchy of any item. Since terms can only have 1 parent, this is all we need: the number of items in this list equates to the term depth level, and even provides term ids.
Usage:
$ancestors = get_ancestors( $term_id, 'custom-taxonomy-slug' );
print_r( $ancestors ) ; // array( 0 => 15, 1 => 45 ) - 3rd level term | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 6,
"tags": "custom taxonomy, terms, hierarchical"
} |
How do I get only a certain number of images from a post (minus the featured image)?
I have the following code (see below) that lists all attached images from a post. I'm trying to alter this code to only list the first five images, and also to exclude the featured image from the list. Any help is certainly appreciated. Thanks in advance.
<div class="entry-content">
<ul>
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );
echo '</li>';
}
}
?>
</ul>
</div><!-- .entry-content --> | Did you try this:
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 5,
'post_status' => 'inherit',
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id( $post->ID )
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "get posts, images"
} |
Trouble using antispambot()
I have a custom field in a theme that contains an email address and was pleased to find `antispambot()`
<p><a href="mailto:<?php antispambot(the_field('queries_e-mail')); ?>"> <?php echo antispambot(the_field('queries_e-mail'));?></a></p>
It looks fine and works as intended (ie. it opens a compose mail window) but when I view the code source it doesn't appear to be encoded.
<p><a href="mailto:[email protected]"> [email protected]</a></p>
According to the Codex the default usage is :
<?php echo antispambot("[email protected]"); ?>
which should output:
john.doe@mysite.com
However the encoding doesn't appear to be working in my case. | I think the problem is **echo** _vs_ **return** ,
i.e. that you are using `the_field` instead of `get_field`.
What you're trying to do is similar to this:
antispambot( echo( '[email protected]' ) )
but `echo` returns nothing.
Please try:
<?php $email = antispambot( get_field( 'queries_e-mail' ) ); ?>
<p>
<a href="mailto:<?php echo $email; ?>">
<?php echo $email; ?>
</a>
</p> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "functions, email"
} |
Confusion on how to display custom field data
Hey I'm new to WordPress. I've looked at the codex and other topics here, I just don't get how to display my custom field, which I have set in the area under my post editor. The name is `MyField` and the value `This is my custom post text`.
Now I want to include my field into the category loop, so it shows up instead of the standard excerpt.
`<?php the_meta(); ?>` shows obviously all custom fields, that is not what I want.
I´ve tried to include `<?php get_post_custom_values('MyField'); ?>`, which changed nothing, do I have to do something with this after that like calling it? How can I do that? | Use: **`get_post_meta()`**:
if ( get_post_meta( $post->ID, 'MyField', $single=true ) ) {
echo get_post_meta( $post->ID, 'MyField', $single=true );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
Weird characters in title if it contain “ ”
If my post title contain `“ ”` all the title stored in the database title column in weird characters like this
`"الأورومتوسطى للشباب" تبدأ تلقى استمارات أنشطة الجمعيات الأهلية`
I searched more & more but all i found is some advices to change the table encoding to `UTF8` it is already `UTF8`
After some tests i found that the problem is came from `feedwordpress` plugin not from WordPress itself
How to solve this? | The Solution is:
every normal character stored in weird starts with `&#` ends with `;` like this `٪`
So you can simply 1-open you dreamweaver
2- new HTML file
3- code tab
4- delete all the code in it
5- put one weird code like this `٪`
6- design tab
7- you can see the original character here
8- execute this sql query in `PHPMyAdmin`:
`update en_posts set post_title = replace(post_title, 'one weird chracter code', 'original character');`
9- repeat this method for every character
10- save your sql queries in txt file
11- execute all this queries every few days
The benefits of this cleaning method:
1- for big wordpress installation this will decrease your database size & speed up your site performance
2- if you using `getposts` or `wp query posts` to execute posts by `s=keyword` all the weird posts will not shows in your query
this is very fine at least for me | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, title, feed"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.