INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Rollover button doesn't appear in sidebar
For some reason, I can't add a PayPal donate button to the sidebar of my website. I've been using CSS to create a rollover effect, and while it's worked on a static page of my site: < the same method doesn't appear to work in the top widget on the right sidebar of the site.
### CSS:
a.paypalButton {
display: block;
width: 207px;
height: 44px;
background-image: url('
}
a.paypalButton:hover {
background-position: bottom left;
}
### HTML:
<a class="paypalButton" href=" </a>
I even added the button to the bottom of the volunteer page (< and it works there, but just doesn't show up in the sidebar. If I write text between the a tag it places the button as a background, but that's definitely not what I want to do. | solution for your problem
1.This css code conflict with your css ( for paypal button )
#widgets .textwidget a {
display: inline;
}
and
#widgets a {
display: inline-block;
margin: 0;
padding: 0;
text-decoration: none;
}
2.put !important in display property
a.paypalButton {
display: block!important;
width: 207px;
height: 44px;
background-image: url('
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "css, html, widget text"
} |
Add Parent to Subpage List
Below is the best code I could find for producing a list of subpages _and_ the parent page. However, it only shows the parent page while on the subpages. How do I get this to display the parent page when the user is on the parent page also?
<?php
if($post->post_parent){
$children = wp_list_pages("title_li=&include=".$post->post_parent."&echo=0");
$children .= wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
} else {
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}
if ($children) { ?>
<ul class="subpages">
<?php echo $children; ?>
</ul>
<?php } ?> | <?php
if($post->post_parent){
$children = wp_list_pages("title_li=&include=".$post->post_parent."&echo=0");
$children .= wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
} else {
$children = wp_list_pages("title_li=&include=".$post->ID."&echo=0");
$children .= wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}
if ($children) { ?>
<ul class="subpages">
<?php echo $children; ?>
</ul>
<?php } ?>
Try that. Just have to include the parent much like you do on the child pages, but using the current $post-ID. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp list pages"
} |
How to make Home Menu( Front Page) use index.php instead of page.php
I needed a "Home" menu item in my wordpress website, so I created a new page and named it "Home", added it to my main menu item and then from Reading Settings I selected the "Home" as Front Page.
Now the problem is, the `Home` is using `page.php` instead of `index.php`. I really need to get the home page using index.php as I have already designed the front page in my index.php
Could you please tell me how to make the home page use index.php instead of page.php | The simplest way would be to duplicate your index.php in to a file named home.php in your theme's folder.
Another way would be to create a new page template same thing (copy index.php into it) and add this at the very top
<?php
/*
Template Name: My Home Page
*/
Then head over to the page edit screen and select "My Home Page" from the template drop down
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, homepage"
} |
How can i add a submenu to a custom menu of another plugin?
I'm writing a couple of plugins. One plugin would be the core plugin with certain bits of functionality.
The other plugin would extend that functionality.
What I've done is in the CORE plugin, I've created a menu using "add_menu_page" and I also one submenu page in that menu.
Now, as users add more extension plugins I want to add new settings menu items under the CORE plugin menu.
I tried using add_submenu_page in the extender plugin and this adds the submenu. Problem is it gets rid of the main menu sublink in the menu. The link is added to the menu, but when i click it it does not load the right page. I get a 404.
I'm curious what command should I use to add a new submenu page to an already existing admin menu? | Always happens. I ask and immediately find the answer.
The answer is in the 2nd plugin add a "priority" of 11 to the add_action command. This plugs that submenu right in there.
Like this: `add_action('admin_menu', 'admin_submenu', 11);` | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "plugins"
} |
Ascending Order is not Working in Custom Post Type Listining
Can you please let me know why this code is not listing Custom Post Types?
<?php
$loop = new WP_Query(
array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'name',
'terms' => 'ne',
'order' => 'ASC',
)
),
'posts_per_page' => 10
)
);
?>
<?php
if ( $loop->have_posts() ) :
echo '<ul>';
while ( $loop->have_posts()) : $loop->the_post();
$custom = get_post_custom($post->ID);
echo '<li>'.the_title().'</li>';
endwhile;
echo '</ul>';
endif;
?>
Thanks | If you want to sort the custom post type `'product'` by title, please try:
array( 'post_type' => 'product',
'posts_per_page' => 10,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array( 'taxonomy' => 'genre',
'field' => 'slug',
'terms' => 'ne',
)
)
)
where `'field'` can in general be either `'id'` or `'slug'` (ref). You can check the available `orderby` input parameters here. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, order"
} |
Redirect After Delete User in Backend
How do I **redirect** to a certain page **after user deletion**?
For demonstration purpose, let's say I want to **redirect to the dashboard on user subscriber deletion**. This is what I have tried so far:
function mod_redirect_subscriber_delete($user_id) {
$user = get_user_by('id', $user_id);
$role = $user->roles[0];
if ($role == 'subscriber') {
wp_redirect( admin_url('/index.php') );
exit;
}
}
add_action("delete_user", "mod_redirect_subscriber_delete");
The above code successfully redirected me to the dashboard, but the **user didn't get deleted**.
I had also tried `deleted_user`. This deleted the user but it didn't redirect.
Any ideas?
Cheers! | You could also do this,
function mod_redirect_subscriber_delete($user_id) {
$user = get_user_by('id', $user_id);
$role = $user->roles[0];
if ($role == 'subscriber') {
add_action("deleted_user", function(){
wp_redirect( admin_url('/index.php') );
exit;
});
}
}
add_action("delete_user", "mod_redirect_subscriber_delete");
Anonymous functions (closures), available in PHP 5.3+.
Benefits:
* No need to remove the initial hook on `delete_user`
* No need to re-run `wp_delete_user()`
* You still get to hook onto `deleted_user` because we retain the user's role within the function, hence we place our closure in the `if(conditional)` statement. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "redirect, user roles, customization"
} |
how to add custom word press regisration form in word press 3.5 with out module
i want to add custom registration form in wordpress 3.5 ..with out module i tried few code samples in net seems to be not working with 3.5 properly | If you want to create custom register page then you use in wp-users Table
wp_create_user();
It will create the user and if you want to add custom field then save that field data in wp-usermeta table using
update_user_meta();
and last if you want to add role to the user then use
$u = new WP_User( $user_ID);
$role_of_user= $u->roles[0];
$u->remove_role($role_of_user);
$u->add_role('your_role'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "login, user registration"
} |
Can I force get_option to go back to the DB instead of cache?
Is there any way to guarantee that when I call get_option I will definitely get the value from the database and not from cache? | You could delete an existing cache for your option before you call `get_option()`:
$GLOBALS['wp_object_cache']->delete( 'your_option_name', 'options' );
$value = get_option( 'your_option_name' ); | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "cache, options"
} |
Displaying content to search engines but via navigation only for registered users.
Displaying certain information depending on if a user is registered is quite easy as I have been using this code
<?php if (current_user_can(‘subscriber’)) { ?>
[content here]
<?php } ?>
However, is there any way that this content is visible if somebody directly comes to the link via a search engine or link but not via the archive pages /site links. Help is appreciated. | You can detect where the user comes from (like Google) using `HTTP_REFERER`.
<?php
if (strpos($_SERVER['HTTP_REFERER'], "google") == true) {
echo "Hello Google User!";
}
?>
So for your logged-in user:
<?php if ( current_user_can( 'subscriber' ) && strpos( $_SERVER['HTTP_REFERER'], 'google' ) ) { ?>
[content here]
<?php } ?>
**Important Links**
1. `wp_get_referer()` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, user roles"
} |
How to handle shortcodes through plugin
I learned that I can only put in the code for handling my shortcode through the theme's `functions.php`
But I was thinking of making it a plugin rather than a theme. How can I achieve that? | There is no difference. This is a complete shortcode plugin:
/* Plugin Name: blogname */
add_shortcode( 'blogname', 'get_bloginfo' );
Usually, you should never register shortcodes in a theme, because the content will be useless after a a theme switch. So, a plugin is the better option. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugin development, shortcode"
} |
Best place to call xdebug helper functions?
Right now I place the following code wherever I expect something to go wrong.
/** xdebug helper */
error_reporting(E_ERROR);
ini_set("display_errors", 1);
ini_set("html_errors", 1);
Where should I include this code so that it's always called on every page? | They recommend putting it into the wp-config.php file.
You can read more about it from the codex Editing wp-config
It is quite a long document but the error info is found at **2.15 Configure Error Logging** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "debug, customization"
} |
Setting limit to posts or page creation
This is regardging to On multisite installation and setting limit to content creation by sub-site admins.
I want to set a limit for posts,pages or any custom post types for any sub-site admins. So that they could just create certain number of pages and not more than that. I don't know what filter could help to set limit in functions.php.
Could any one help me with that? So that I could achieve it?
Thanks! | **Important Link:**
1. Posts Creation Limits
Dig into this plugin you easily get the code for limit posts/pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, pages, limit"
} |
Redirect url in plugin to somewhere else?
I am using **WP-SNAP Extended! v1.0.0** and I want to use this alphabetical menu as a sub-menu beneath my header. I managed to get the alphabetical menu in place, but now, if I click on a letter, it will show the posts on the page I am looking at and that is not good, because it overlaps the things that are already there. So you get a very chaotic website with many different content..
What I want to do is this: if I click on a letter, I want it to redirect it to a page where I output the posts that are with that letter. Now, it shows: **< if I click on a letter. I want it to show **
How do I pull this off? I am using this function to get it: `<?php if (function_exists('wp_snap')) { echo wp_snap(); } ?>` | I've solved it with hard coding. I know, it isn't a great answer, but there was no other choice. Redirecting this plugin wasn't possible. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, menus, pages, redirect"
} |
Where does the time get pulled from in the_time()
I am currently using the following function in my footer
<?php the_time( 'Y' ); ?>
But the footer keeps showing 2011, instead of 2013.
So where does this time stamp get called from exactly? | `the_time()` is for outputting the time at which a post was written, and gets this value from the global `$post`.
I'm guessing you just want php's `date()`? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "date time, timestamp"
} |
Better handling of WP-CRON server load abuse
There are multiple reports on how wp-cron is a far from ideal solution because it runs every time a page is loaded, which is unnecessary in most scenarios (one scenario in which it would be necessary is when you use _scheduled posts_ )
The common advice is to add `define('DISABLE_WP_CRON', true);` to wp-config.php then schedule a real cron job (if you have enough admin access to so).
But **as of WP 3.3, there isWP_CRON_LOCK_TIMEOUT**, which " _defines a period of time in which only one cronjob will be fired_ ".
If you run hundreds of WP installs you would have to create (and delete, when that wp install is removed) a LOT of cron jobs, which can become a nuisance. Therefore, it **seems that the best solution these days is setting`define('WP_CRON_LOCK_TIMEOUT', 900);`** (if you want wp-cron to run every 900 seconds).
**The question is: has anyone used WP_CRON_LOCK_TIMEOUT with this purpose yet? Is this its intended use?** | This is the intended use of the `WP_CRON_LOCK_TIMEOUT` constant.
When WordPress is loaded, it checks to see if a cron job is running (if cron is locked). If cron is not locked, it will try to create a lock - if the lock timeout has not been reached, no lock can be acquired and cron is not run.
If no cron job is running, and the timeout has passed (meaning a lock can be created), then cron is run. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "cron, wp cron, scheduled posts"
} |
changing the labels inside appearance -> menus for some for the fields
So I've create a custom walker for nav menu (i am talking about the menus located at: appearance -> menu -> add a new menu. I now use the following for several things i need: `URL` `Title Attribute` `CSS Classes (optional)` `Description`
My question is how do i change the labels of those fields to be more explanatory toward my uses.
So instead of title attribute for example it will say something like `menus width`
Thanks in advanced. | I don't have the time to work out a complete solution (which could be pretty complex) but, if I am reading things right, by default WordPress uses `Walker_Nav_Menu_Edit` to create those backend menus. It looks to me like you can build your own walker for the backend and pass it in via the `wp_edit_nav_menu_walker` hook.
If you did that, you should be able to not only rename those fields but add your own fields to keep things neat. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, navigation, walker"
} |
wordpress url with format .com/category/sub-category
I may be overlooking a simple answer here, but this one is stumping me. I am converting a site to wordpress. The current site has many pages whose URL has the format www.x.com/category/topic.
What I cant figure out/remember, is how to create a page or post with that format. As far as I know, the standard wordpress format is www.x.com/category
It is important to keep the integrity of these links, so keeping the exact destinations is a must. I would like to accomplish this without the use of redirection plugins.
Thank you in advance. | You can use structure tags in `Settings` > `Permalinks` > `Custom Structure` to form something like `/%category%/%postname%/`.
That is if your "topics" will be posts. Pages or terms might be more involved to deal with. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "urls"
} |
Covert Wordpress Blogname into JQuery
Here is the blogname in php `<?php $blog_title = get_bloginfo('name'); ?>` I want to convert it to javascript. The file I want the blog name is in a .js file so I cant create the variable with php. | Use `wp_localize_script`
function set_js_var() {
$translation_array = array( 'blog_name' => get_bloginfo('name') );
wp_localize_script( 'jquery', 'my_data', $translation_array );
}
add_action('wp_enqueue_scripts','set_js_var');
If you look at the source of the page you will see something like:
<script type='text/javascript'>
/* <![CDATA[ */
var my_data = {"blog_name":"WordPress 3.5.1 Release"};
/* ]]> */
</script>
That is your Javascript variable.
You have to "register" that on some existing Javascript slug. That is, some slug you've already used to register a script. That is why I used `jquery`, which is the slug used by WordPress to load its bundled `jQuery` library. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, jquery, javascript"
} |
Allow users of my plugin to define their own shortcode rather than use mine?
I'm creating my first plugin. So far everything is great, but my shortcode is something like this `[BIMS]` and that acronym might not be easy to remember, or appeal to everyone. I'd like to include an option to have them input their own replacement shortcode.
What is the proper code to allow them to use their own shortcode text yet bring up my function? | Save the shortcode name in an option, and use that when you add the shortcode:
add_shortcode(
get_option( 'your_plugin_option', 'default_shortcode_name' ),
'your_shortcode_callback'
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, plugin development, shortcode"
} |
Accessing two databases
I have two databases on my server, and wanted to know is there a way to access both databases from wordpress? My thought is adding the second set of credentials to the `wp-config.php`. | You can easily set up another `$wpdb` object to access your other database.
$mydb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
var_dump($mydb);
That, of course, uses the default connection credentials but if you defined different constants and used those, is should work just fine.
If this other database is not a WordPress database, you won't have some of the functionality offered by the `wpdb` class but the basics should work if you write the SQL. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "database, wp config"
} |
What makes a placeholder resizable in Tinymce?
It's not that hard to make a plugin to TinyMCE, similar to what the Wordpress gallery is doing in WP 3.5. Unfortunately, these custom placeholders are always non-resizable, although they show the resizer handles.
A new image inserted into a post is resizable with the handles, an embedded iframe is resizable, but a new gallery placeholder is not resizable (in this case it doesn't make sense, galleries don't resize). However, I need a custom placeholder that **is** resizable. Is there a special class that turns this on or off, or a function that I need to call to enable resizing on a certain element? | Looks like removing the height: and width: from the css makes it resizable :)
I had copied css with those settings. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, gallery, tinymce, plugin tinymce"
} |
WordPress keeps resizing my 947x947 image down to 500x500 (full-size option)
This is driving me crazy. The code for the image is: `<img src="MYLINK" />`
Yet it keeps resizing my image down to 500x500 from 947x947. How do I fix this?
Also, it disregards the image map I have which lets you click on different parts of the image to go to different sites.
EDIT: This is what I'm referring to: < Right click and check the image properties: it shows how the 947x947 has been scaled to 500x500. | I figured it out. The hint from user29296 is what led me to this: I had to insert the image using CSS, not html. Check the page now: <
The code was this:
<style type="text/css">
#image
{
position:absolute;
width:947px !important;
height:947px;
background-image:url('
background-repeat:no-repeat;
}
</style>
<div id="image"></div>
Thanks for the replies! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Want to modify a Plugin - Tweetily - Can I make it tweet a Custom Field instead of Post Title?
<
I was wondering if somehow it's possible to make it tweet a Custom Field instead of Post Title?
in top-core.php, at line 214
if ($tweet_type == "title" || $tweet_type == "titlenbody") {
$title = stripslashes($post->post_title);
$title = strip_tags($title);
$title = preg_replace('/\s\s+/', ' ', $title);
} else {
$title = "";
}
Can I replace post_title with something else which can do the trick? | Sure you can do this with :
$title = stripslashes( get_post_meta($post->ID, 'key', true) );
You just have to replace 'key' with the appropriate key.
See the documentation | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, customization, hacks"
} |
forward domain name to particular page?
I;ve got a doman alias setup for one of my Wordpress sites and i'm trying to forward that particular domain to a page.
The 2 domains are -
www.alias.com www.actual.com When people use the _www.alias.com_ domain i want them to be forwarded to _www.alias.com/content/_
I've tried several things with the htaccess file but i think Worpdress may be ignoring the redirects or i've got it completely wrong!
ie
Redirect 301 www.alias.com
# and
RewriteCond %{HTTP_HOST} ^www.alias.com
RewriteRule (.*)$ [R=301,L]
best, Dc | First off -- does your server allow overrides in `.htaccess` files? If not, you need to get that turned on. My server has `AllowOverride All` set in its config file, which then allows my `.htaccess` rules to function.
Does `alias.com` point to the same directory as `actual.com`? If not, then you need to put a `.htaccess` file in the `alias.com` root.
Also, if I understand your requirements correctly, the `.htaccess` file for `alias.com` needs to contain this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.alias.com$ [NC]
RewriteRule ^(.*)$ [R=301,L]
### References
Apache's Config File & URL Rewriting docs
I also have a mod_rewrite from < but that site seems to be down now. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "redirect, htaccess, domain"
} |
Replacing WordPress Icons (menu,icons32, etc)?
I want to replace wordpress admin sprites. I recreated the images and looked answrs for icon replacement using jquery and simply with CSS BUT what about ones link icons32-2x.png where I can't find the CSS?
So I am trying to figure out a simple way to redirect the wordpress admin and includes folder to use my new icons INDIVIDUALLY.
Again this is just not for custom post type icons but all.
Basically I think through jQuery using replaceWith new icon but how can I replace an image if I don't know where its called in CSS (i.e. retina images) so I need a resolution to direct specific images in admin wp-admin and wp-includes folder.
* mydomain.com/wordpress/wp-admin/images/
* mydomain.com/wordpress/wp-inlcudes/images | The CSS is in `wp-admin/css/colors-classic.css` and `wp-admin/css/colors-fresh.css` and the `min` versions of those, including the `icons32-2x.png` ones. I can see them when I `grep` the directory. For example, `wp-admin/css/colors-classic.css:2162`.
The images themselves are in `wp-admin/images`, as you can see from the style rules, but you should not be hacking/replacing those. They will be overwritten when you update WordPress.
I don't see the need for Javascript at all. You can register stylesheets for the backend. That should be all you need. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, jquery, javascript, html, icon"
} |
Total number of authors with more than one post
<?php
$users = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");
echo '(', count( get_users( array( 'role' => 'author' ) ) ); echo ')'
?>
code by Jan Beck
I need to know what is my best option for displaying the total number of authors who have at least posted and/or published something on my blog.
Currently the code is counting all the authors even if they haven't posted anything. Please let me know if there is a simple solution to this. I have looked throughout the wordpress codex and have not found a solution to this yet. | I believe that `wp_list_authors` will do what you want, sort of. You could run the function with the `echo` parameter false and count the results.
$authors = wp_list_authors(
array(
'echo'=>false,
'html'=>false
)
);
echo var_dump($authors);
echo count (explode(',',$authors));
Or, alternately, and perhaps less profligately, steal that function's `SQL`.
$authors = $wpdb->get_results(
"SELECT DISTINCT post_author, COUNT(ID) AS count
FROM $wpdb->posts
WHERE post_type = 'post'
AND " . get_private_posts_cap_sql( 'post' ) . "
GROUP BY post_author"
);
var_dump($authors);
echo count($authors);
Those are slightly different in that the first ignores the admin user by default, but there is a parameter to change that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users"
} |
Make WordPress size and name images for Retina.js
I'm a huge fan of the way retina.js works for high pixel density displays. Essentially, when it's loading image assets (via `<img>` or css image) it will check if there's a `@2x` suffix version of the image (eg. if there's a `logo.jpg` it will automatically show the `[email protected]` in its place if it exists.
The WordPress function `the_post_thumbnail` lets me define various image sizes, but I want to know if there's a way to have it also create versions of the images that are twice the size with the `@2x` suffix as well!
It's easy to do this for theme files, but would be pretty awesome to allow this for content images as well. | Check this Wordpress plugin
Wp Retina 2X | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "functions, post thumbnails, content"
} |
Need to block user role from accessing bbPress all together
I've been looking at some options and I haven't seen a full solution to what I need. I need to block certain `user_roles` from accessing bbPress all together and from seeing the link to the page.
Any pointers? | Check this plugin. I've used it and it's quite versatile regarding user roles and user capabilities.
You can also add conditional statements in your php files, like this:
if (!current_user_can('some_capability_you_added')) {
echo "You don't have permission for it!";
return;
}
You can output that sentence or nothing at all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user roles, user access, bbpress, private"
} |
Page specific values in widgets
I have a travel guide website which I have created with WordPress which contains destination guides. On the destination guides pages I have a sidebar which displays destination statistics (currency, time zone etc).
Currently I have to create a new sidebar for each page each time changing these values.
Is it possible to create a MySQL database with these values and then insert some PHP code that will identify what country page is loaded and insert the corresponding values so that I can use a single sidebar for all pages. I am fairly proficient with HTML/CSS, but my understanding of PHP is limited.
How can I do that? | Add the data to your pages as Custom Fields, then use one of the meta functions in your sidebar to display this data.
Note that the custom fields UI may be hidden from view on pages. If this is the case, click the Screen Options tab in the upper right corner and tick the box next to Custom Fields and the UI will appear. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, widgets, sidebar"
} |
Allow author to choose his featured image size
Request from a client. He wants his authors to be able to upload their image and then set it as featured, just like normal. The difference is that when setting it as featured, he wants the author to be able to choose 'small' or 'large' which will then be output appropriately on the front-end. How would you go about this? I'm well aware of how to create new image sizes in the theme, but how can I allow the author to select his image size when making his post? | You could add a meta box to the post add/edit screen below the featured image box to allow selection of size via a dropdown select menu. You could generate the list from available sizes (via `get_intermediate_image_sizes`), or just use your small/large strings. The data would be saved as post meta and you would simply `get_post_meta()` to get the selected size, then pass that result to the thumbnail function as the size parameter. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
Add multiple pages to theme customizer
So that theme customizer over at `/wp-admin/customize.php` is pretty cool, but it looks like it only lets you customize one page. Is there any way to add multiple pages or other theme template pages to this customizer? | Pages cannot be explicitly "added" to the customizer - to view other theme templates, create pages first then click through the site links in the customizer view. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, theme options, theme customizer"
} |
what could cause the htaccess file to be modified?
One of the wordpress sites that I created recently went down with a _500 internal server error_. After hours of mind boggling and checking error logs, I found out that the `htaccess` files present in the user directory had been modified, with an `ss` added to the end of the file which caused the error. After changing and uploading the file, the site got back up.
I wanted to know what could have caused this? It is hosted on a godaddy server, and the permission for the file is 604. was the server hacked or did wordpress somehow write this into the file.
Thanks. | This might happen when the rewrite rules are flushed. The function `insert_with_markers()` is using `fopen()`, but _not_ `flock()`, so when two pieces of code are calling `flush_rewrite_rules()` almost at the same time, the second process can write to that file before the first one has closed it.
Check your plugins and your theme for `flush_rewrite_rules()`, especially those registering custom post types or taxonomies. Some poorly written plugins are calling this on every page load. Disable that plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "htaccess, ftp"
} |
Checking for existing title in custom db query not working
I want to check if the title exists before the `wp_insert_post()` is triggered.
However, the condition seems not to work as expected:
if( $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . trim($titles_arr[$i]) . "' AND post_type=post", 'ARRAY_A') ) {
// title do exist
// don't save
} else {
// ...perform save code
}
And it saves always no matter if it exists.
The funny part is that if the existing title i my db is e.g.: `The best title in the world` and slug `the-best-title-in-the-world` and for example one thing from the `trim($titles_arr[0])` (I am looping the array via foreach loop) array than the slug of that post that shouldn't be saved in the first place is called `the-best-title-in-the-world-2` and if I run my scirpt again it became `the-best-title-in-the-world-3` etc. | use get_page_by_title to get post by title.
I check for it on my system
$post_exist=get_page_by_title( 'Hello world!', ARRAY_A, 'post' );
if( ! empty( $post_exist ) ) {
echo 'title exist';
} else {
echo 'title not exist';
}
Running successfully.
In your case it may be like
$title=trim($titles_arr[$i]);
$post_exist=get_page_by_title( $title, ARRAY_A, 'post' );
if( ! empty( $post_exist ) ) {
echo 'title exist';
} else {
echo 'title not exist';
}
see also:Get WordPress Post ID from Post title | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, query"
} |
Archive page for custom post type not working
I use a plugin called CPT-onomies to create Custom Post Types. I created a post type called "case", and set "Has Archive Page" to true, but when i try to view a single case, i just get 404'd. Same thing also happens if i try to view the actual archive, eg. "site.com/case" and not "site.com/case/case-item".
Here's a screenshot of my settings:
I've tried disabling/enablind it, no success. I also tried changing permalink structure of the whole site (from settings -> permalinks) because sometimes that doesn't update.
Have i missed something in the settings or is this a bug in the plugin? I've gone through it several times and i can't find anything that would prevent it from working.
I have a template file called `single.php` that should be used. I also tried `single-case.php` but that didn't make any difference.
# Solution
I found a solution here: < | I found a solution here: <
Here's what you need to do to get it to work (quoted from site above):
1. Go to Settings → Permalinks and change your current structure to: /%category%/%postname%
2. Save changes.
3. Restore your original permalink settings. Save changes. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "custom post types, single, custom post type archives"
} |
WordPress Loop: List All Posts by a Category & Subcategory
I want to display all post under a category and all subcategories under the parent categories. But couldn't find proper suggestion over forum or failed to understand the solution. It's possible to perform this tasks by manually adding add ID into query but for me, I need all to be autopopulated.
Need suggestion. | The `cat` and `category_name` parameters for `WP_Query` display "posts that have this category (and any children of that category)".
There are also examples of doing this in the Codex.
$query = new WP_Query( 'cat=4' );
// or
$query = new WP_Query( 'category_name=staff' );
I am not 100% sure what you mean by "I need all to be autopopulated", but if you want WordPress to "just know" what category you want there is no such ESP-based function in either WordPress or PHP. You have to tell the query what category to use, but you don't have to hard-code to `ID` or the name. It may be possible to _logically_ derive the appropriate category but you have not provided any details _at all_ about what the criteria would be for making that decision. You don't even say what page you are on, or whether you talking about the front or the back end. Without that detail a better answer is going to be difficult. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "query"
} |
Automatically add author's name to post_tag
I need to add the author of a post's name to the post's tags whenever the post is published. So for example John Smith wrote a post, the tag 'John Smith' would be added to that post's tags.
I've tried a couple of different ways, but I think I'm closest with this:
In functions.php:
add_action( 'save_post', 'add_authors_name');
function add_authors_name( $post_id ) {
$post_author = get_the_author($post_id);
wp_set_post_terms( $post_id, "$post_author", 'post_tag', true );
}
This doesn't work, but I think I'm getting there. Just not sure what I'm missing... Could anyone shed some light on this? | Check get_the_author()
( **Note** :This tag must be used within The Loop.)
you code may be like this In functions.php:
add_action( 'save_post', 'add_authors_name');
function add_authors_name( $post_id ) {
global $post;
$post_author = $post->post_author; // returns the Author ID
// get the author's WP_User object so we can get the Author Name
$post_author_obj = get_userdata( $post_author );
$post_author_name = $post_author_obj->first_name . ' ' . $post_author_obj->last_name;
wp_set_post_terms( $post_id, $post_author_name, 'post_tag', true );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, tags"
} |
How we show pages in dropdown
I show the all `menu` which i have on the top in `dropdown` style when site is open in mobiles. I successfully display them in dropdown style but the problem is that how can i indend my subpages. or make parent pages bolg is any way to do that, my code is
<nav id="nav-mobile" role="navigation">
<select id="mob_menu" name="page-dropdown">
<option value="">
<?php echo esc_attr( __( 'Select page' ) ); ?></option>
<?php
$pages = get_pages();
foreach ( $pages as $page ) {
$option = '<option value="' . get_page_link( $page->ID ) . '">';
$option .= $page->post_title;
$option .= '</option>';
echo $option;
}
?>
</select>
</nav> | Use `wp_dropdown_pages()`:
print '<form action="' . home_url() . '">';
wp_dropdown_pages();
print '<input type=submit></form>';
You get a `select` field with proper indentation, and clicking on the button will send the user to that page.
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
How to send "Location" header on plugin form submit event?
How to redirect to specified page after form was submitted?
> Warning: Cannot modify header information - headers already sent by (output started at `wordpress\wp-admin\menu-header.php:94`) in `wordpress\wp-content\plugins\test\test.php` on line 16
<?php
/*
Plugin Name: TEST
Plugin URI:
Description: TEST
Version: 0.0.1
Author: TEST
Author URI:
*/
add_action('admin_menu', 'test');
function test() {
add_menu_page('test', 'test', 0, 'test/test.php', 'page');
}
function page() {
if(isset($_POST['submit'])) {
header('Location: /index.php');
exit;
}
echo '<form action="" method="post"><input type="submit" value="Submit form" name="submit" /></form>';
var_dump($_POST);
} | You're trying to send a redirect header on the `admin_menu` action, which is fired after some of the page has been sent to the browser. You have to hook an earlier action before output starts, like `init`.
add_action( 'init', 'wpa_test' );
function wpa_test() {
if(isset($_POST['submit'])) {
wp_redirect( home_url() );
exit;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, redirect, headers"
} |
Adding Pipes to Menu Output
My client has a menu like this image below that I am trying to re-produce for them as a WordPress Menu...
!enter image description here
My first attempt so far was to utilize the `after` parameter option for the `wp_nav_menu`.
Below you can see where I have passed in `<span class="navSep">|</span>`
This adds the `Pipe` after each menu item. I need to somehow make it not add to the last menu item or else it does not look right having an ending pipe.
Any suggestions? I would rather stay away from using JavaScript to hide/remove the last item.
I am open to anything as long as I can output the menu like the image below?
wp_nav_menu(
array(
'menu' => 'footer-menu-1' ,
'after' => '<span class="navSep">|</span>'
)
); | You could build a custom Walker that would either not insert that on the last field or insert classes you could use, but if this is the only change you want that would be overkill. Hide it with CSS. Something like...
.menu li:last-child .navSep {
display:none;
}
I guessed at the CSS but that is the general idea. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
Mystery ghost page not appearing in Admin
I have a strange problem.
I have a blog listing page like example.com/something but this page is no where to be found in the admin.
It returns 200 OK http status so its there.
But it uses a seemingly random template and looks broken.
What can I do?
How can I find it in admin?
The usual tricks dont work.
* There is no id to be found in the HTML source (no shortlink etc)
* searching for the permaling slug in admin doesnt return anything
What else could I try? | For anyone interested, it was the SEOyoast plugin that caused the problem.
I turned it off and on, than the page appeared again in the admin.
After that I rest the settings for the page and it now works as expected and accepts its template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, pages, admin"
} |
Gravity Forms, how to link form to amember pro signup
Trying to linkup a custom gravity form to my aMember Pro signup form and having difficulties.
I have this for my in my functions file:
// Gravity Forms to aMember Pro Link Up
add_action("gform_after_submission_5", "after_submission", 10, 2); // Run these scripts strictly on Form ID 5
function post_to_third_party($entry, $form) {
$post_url = '
$body = array(
'name_f' => $entry['3'],
'name_l' => $entry['4'],
'email' => $entry['1'],
'login' => $entry['2'],
'pass' => $entry['5']
);
$request = new WP_Http();
$response = $request->post($post_url, array('body' => $body));
}
I have tried the post_url as 1. < 2\. < and 3. <
with no luck. Wondering if anyone here has tried to link these 2 systems up. Found threads online but haven't been that helpful. | I believe this code (as is) will never call your `post_to_third_party` function. The `add_action` hook needs to reference that function like so:
add_action("gform_after_submission_5", "post_to_third_party", 10, 2);
Hope that helps, have fun! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin gravity forms, membership"
} |
get_post_types is not showing all registered posts
When I call get_post_types() in a plugin the output is registering only the basic set of post types. Here is the output:
array(5) { ["post"]=> string(4) "post" ["page"]=> string(4) "page" ["attachment"]=> string(10) "attachment" ["revision"]=> string(8) "revision" ["nav_menu_item"]=> string(13) "nav_menu_item" }
In this wordpress theme, however, I have registered a custom post type called 'artist', but it is not showing up. If, however, I call get_post_types() in the index.php file it does how the registered posts:
array(8) { ["post"]=> string(4) "post" ["page"]=> string(4) "page" ["attachment"]=> string(10) "attachment" ["revision"]=> string(8) "revision" ["nav_menu_item"]=> string(13) "nav_menu_item" ["acf"]=> string(3) "acf" ["artist"]=> string(6) "artist" ["release"]=> string(7) "release" }
Does anyone know why this is happening and how to get around the problem? | You have to wait with your call until the theme has registered its post type (it really should not do that anyway):
add_action( 'after_setup_theme', 'list_post_types', 20 );
function list_post_types()
{
var_export( get_post_types() );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Detect Post Type when publish_post is ran
I currently have WordPress build an `XML Sitemap` everytime a `POST` or `PAGE` is `PUBLISHED` by using this Action...
add_action("publish_post", "create_news_sitemap");
I am not doing the same process but for a `News Sitemap` which has different criteria. Such as it can only show post that are no older then 48 hours.
I have my code working but I would like to optimize it slightly.
So when `add_action("publish_post", "create_news_sitemap");` is ran, I would like to ONLY run a function is it is a Custom Post Type named `news` that is Publishing a post.
Is this something that is possible?
when the `publish_post` action is ran, can I detect which POST_TYPE is setting it into action? | `publish_post` will give you a second parameter if you ask for it. Notice the fourth parameter of the `add_action` call. That is your post object.
function run_on_publish_wpse_100421( $postid, $post ) {
if ('news' == $post->post_type)
// your code
}
}
add_action('publish_post','run_on_publish_wpse_100421',1,2); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "posts, publish"
} |
How to add post count to wp_nav_menu?
Is it possible to add post count to menu links using wp_nav_menu?
For example:-
Apple (3)
ball (6)
cat (2) | Basically the easiest thing should be a callback to the `start_el()` method of the Walker class.
// From core:
apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
Just grab the data (whatever the actual data is and from wherever it comes) and append it.
add_action( 'walker_nav_menu_start_el', 'wpse_10042_nav_menu_post_count', 10, 4 );
function wpse_10042_nav_menu_post_count( $output, $item, $depth, $args )
{
// Check $item and get the data you need
printf( '<pre>%s</pre>', var_export( $item, true ) );
// Then append whatever you need to the $output
$output .= '';
return $output;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "posts, menus"
} |
How do I add tags/taxonomy to images + a query field on page to query 'albums' (images with same tag/taxonomy)
I've got lots and lots of photos on my site and I want to seperate them into albums. Every album is a client album (photoshoot).
Though.. I want all my clients to query their album on my site. Something like: *Go to site, page "View your album!", fill in a search bar with unique id (e.g. Client.001.2013) and click non 'Show'. Now they see all their photos (that share the same id, (e.g. Client.001.2013).
So summarized: I need two things (I guess), a way to give all my photos an ID/tag/Taxonomy (back-end) and a search bar on the front end of the site, so people can query those ID's/Tags/Taxonomies, so they see all pictures who share the same ID.
What can you people advise me?
++ for thosesuggestions of a plugin that automatically nicely shows all the queried images in a gallery order or such.
Thanks! | you can search google for WordPress plugins.
check these may be work for you
1. Photosmash Galleries
2. WP Photo Album Plus | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, query, tags, gallery"
} |
JavaScript && operator in visual editor
I am used to of adding javascript/jquery code in posts via visual editor but it seems I never used && operator cause wordpress is altering && operator in &. Here is a link where I am using &&. < I am wondering what is correct way of using javascript in wordpress visual editor. | You should use **wp_enqueue_script** for your javascript files instead of adding the code directly into the post content.
**ps:** You can check out the callbacks on the `the_content` filter, using
add_action('wp_footer',function(){
global $wp_filter;
printf('<pre>%s</pre>',print_r( $wp_filter['the_content'],true));
});
to display them in the footer part of your theme. Then you will see callbacks like `wpautop`, `wptexturize`, `convert_chars` and `convert_smilies`.
I don't recommend it, but it is possible to remove these filters to use javascript code in the post content:
add_action('init','custom_init');
function custom_init() {
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
remove_filter('the_content', 'convert_chars');
remove_filter('the_content', 'convert_smilies');
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, visual editor"
} |
Find all posts via SQL beginning with A of type B
I have problem with post and taxonomy query. What i need is to get all post's from custom post type which starts with A and have defined term. Here is my sql:
SELECT * FROM $wpdb->posts, $wpdb->terms
WHERE post_title LIKE 'А%'
AND post_type = 'filmi-i-serialii'
AND post_status = 'publish'
AND slug = 'igralni';
But this returns me all posts in _filmi-i-serialii_ post-type and not only those that are in the taxonomy _igralni_. | Try this..
SELECT *
FROM $wpdb->posts p
INNER JOIN $wpdb->term_relationships tr
ON p.ID = tr.object_id
INNER JOIN $wpdb->term_taxonomy tt
ON tr.term_taxonomy_id=tt.term_taxonomy_id
inner join $wpdb->terms t
on t.term_id=tt.term_id and t.slug='igralni'
WHERE
p.post_title LIKE 'А%'
AND p.post_type = 'filmi-i-serialii'
AND p.post_status = 'publish' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, advanced taxonomy queries"
} |
Metadata for a taxonomy - is there any WordPress way of doing this?
If I have a CPT "movies" I know I can have various taxonomies eg "Director", but how can I store further information such as "director's nationality" for any one particular director ... or is this possible using WordPress? | why don't you take a look at this I think it it is what you are looking for | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, plugin development, taxonomy, post meta"
} |
Extremely slow Wordpress website with 6000 posts
I have a website with 6000 posts and it is extremely slow.
Sometimes I get this error in my browser:
Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Error: 503 Service Temporarily Unavailable
I have turned almost all plugins off and it is slow in frontend and in backend too, so I guess it is not because of the template.
Could it be because of WP_navigation plugin?
I have est. 600 pages with ten posts or WP navigation plugin, could this be the problem? | Wordpress can be a resource hog if you don't use caching. W3 Total Cache could help you a lot with MySQL, Object and Page Caching. You should also install PHP-APC and use it with the plugin. It can do wonders. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "performance, hosting, cache"
} |
Multiple textdomains
I have a bunch of plugins. Obviously, they all have their own unique textdomains for internationalization (i18n).
I also have a bunch of files that I include in all my plugins - I throw them all in a directory called common. This adds a dashboard widget that I want all my plugins to have, as well as a script for updating (since they don't live on the wordpress.org plugin repo).
I want to be able to just drop my common folder into each of my plugins without having to edit the files. But I'm concerned about the text strings contained inside.
Can I call load_plugin_textdomain twice, for two different domains, within the same plugin? What's the best way of handling this situation with i18n in mind?
Or will I have to go through each instance of my common files and manually change the textdomain to match the plugin? | You can call `load_plugin_textdomain()` multiple times in each plugin, but I would not do that.
Put the _common_ files into a separate plugin, for example `luke-carbis-library`. In that plugin create two simple functions for setup and loading extra files:
add_action( 'plugins_loaded', 'lcl_init' );
function lcl_init()
{
$dir = plugin_dir_path( __FILE__ );
$url = plugins_url( __FILE__ );
// maybe load necessary files and translation
do_action( 'lcl_init', $dir, $url );
}
function lcl_load( $file )
{
require_once plugin_dir_path( __FILE__ ) . $file;
}
In your depending plugins hook into your custom action:
add_action( 'lcl_init', 'depending_plugin_init', 10, 2 );
Now you can change the inner structure of the base plugin any time; the other plugins just use `$dir` and `$url` from your hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, localization, textdomain"
} |
Which action for triggering cron "wp"or "init"?
Which one do you recommend using within a plugin and why?
add_action( 'wp', 'trigger_me' );
function trigger_me() {
if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
}
}
**OR**
add_action( 'init', 'trigger_me' );
function trigger_me() {
if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
}
}
What are the advantages/disadvantages of "wp" over "init" when registering/triggering cron function within a plugin? | Neither.
register_activation_hook( __FILE__, 'trigger_me' );
function trigger_me() {
if ( !wp_next_scheduled( 'my_plugin_cron' ) ) {
wp_schedule_event(time(), 'hourly', 'my_plugin_cron');
}
}
Why parse code on every request when you don't need to? | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 6,
"tags": "plugin development, actions, wp cron"
} |
Styling the second sidebar
Ok so i added a second sidebar to my site, only problem is styling the widgets.
here is the code i am using in my functions.php file
// Widgets plugin: intializes the plugin after the widgets above have passed snuff
function wpbx_widgets_init() {
if ( !function_exists('register_sidebars') ) {
return;
}
// Formats the theme widgets, adding readability-improving whitespace
$p = array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => "</li>\n",
'before_title' => '<h3 class="widget-title">',
'after_title' => "</h3>\n"
);
register_sidebars( 2, $p );
}
I just don't know how to style the second sidebar widget, how do i do this?
I want to use the same code but different class titles | Per the `register_sidebars()` Codex page, the CSS ID of the sidebars gets incremented by default. In other words, if you're not explicitly setting the `id` array value -- and in your code sample above, you aren't -- you would end up with sidebars with CSS IDs of `sidebar` and `sidebar-2`. You can then style them differently in your CSS file (be it `style.css` or a custom one that you've added):
#sidebar {
/* Styles */
}
#sidebar-2 {
/* Styles for the 2nd sidebar */
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, css, sidebar"
} |
Lightbox gallery in a link
Here is what i try to get. Into WordPress a module plugin that allow me to make slideshow of image. create a portfolio name "castle" and another one name "bridge" and get 3-5 photo in each. Then, in a text, i will talk about a beautiful bridge name xyz and i like the name of the bridge to be a link, when i click this link, a modal window will appear with a slideshow (light-box evolution is perfectly what i like), then somewhere else, when i talk about the caste abc i like the name to be a link, when click, show a slideshow of thos 4 image uploaded. so the question, what plugin do that ? thanks for the help !
the way things work in the theme Barely Corporate from ThemeBlvd is AWESOME, but i think it's custom work for there theme !
I try to find a way to get the behavior i whant, i am not promoting any theme or telling this is better that that, i just have seen behavior a like to replicate for my site | You can most likely use Easy FancyBox plugin (and maybe plus NextGen gallery) to achieve the effect.
The FAQ on the Easy FancyBox documents different things you can do: <
For example, you can call lightbox of an hidden image with text link:
<a href="#hidden_image_id" class="fancybox">Castle abc</a>
<div style="display:none"><img id="hidden_image_id" src="hidden_image_url.jpg"></div>
So you'd apply this to a gallery shortcode that output element ID in it's dom:
<a href="#gallery-1" class="fancybox">Castle abc</a>
<div style="display:none">[gallery]</div>
If the native WordPress doesn't work, try the NextGen Gallery or others that would be compatible with how FancyBox tries to find the image sources. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "slideshow"
} |
Is `is_sidebar_active()` deprecated, and showing error?
I **Googled** `is_sidebar_active()`, used by several WordPress trainer, but I came to the decision, the function's surely deprecated. But unfortunately I found no mention, even no entry in WordPress Codex.
As a Wikipedian, I also edit the Codex sometime, but need the confirmation that, `is_sidebar_active()` IS DEPRECATED, and `is_active_sidebar()` is ON now.
I used `is_active_sidebar()` instead of `is_sidebar_active()` in my theme and it's working fine.
But I need a confirmation. Anybody? | `is_sidebar_active()` is not a WordPress function. Do not use that. This is probably a typo.
The correct name is `is_active_sidebar($index)`, and that function is not deprecated. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, sidebar"
} |
What is the use of to_ping and pinged column?
Can anyone explain or show a reference for the use of `to_ping` and `pinged` column in the wp_posts table? It seems that my Googling skills have failed me.
I wanted to do an experiment using the `pinged` column to save the `term_id` of a term that is related to this post record.
I know that the proper way is to use custom field instead, but I wanted to reduce the mysql `inner join` in the WP_Query calls.
Thank you in advance. | * `to_ping` is a list of URLs WordPress should send pingbacks to.
* `pinged` is a list of URLs WordPress has sent pingbacks to.
Do not use these fields for something else. They are parsed many times in core code (69 matches for `to_ping`); their format is fixed.
You cannot reduce the query load by using these fields, because _all_ post meta fields are fetched in one rush per post. So it doesn’t matter if there is one more or less. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 12,
"tags": "posts, table"
} |
How to lock content?
What is the easiest method to make all my articles accessible only to registered users?
My homepage contains titles and excerpts but I want to allow access to the full content only to registered users.
I remember there was an admin setting for that but I cannot find it.
Maybe Im wrong. Any ideas?
Thanks. | You could hook into `template_redirect`, check if it is a singular page (post, page, custom post type) and force a log in:
add_action( 'template_redirect', 'login_to_see_content' );
function login_to_see_content()
{
if ( is_singular() && ! is_user_logged_in() )
auth_redirect(); // does nothing for logged in users
}
As suggested by @s_ha_dum in the comments, an additional `! is_user_logged_in()` might be necessary. In theory, it shouldn’t (and it isn’t in my setup). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts"
} |
Is there a way to password-protect part of a post?
Is there a way to have a page displayed to the public, but have an extra custom field that doesn't display unless a password is entered?
I suppose I could do entirely manually without WordPress functions at all but I'd like to know if there was a WordPress solution. | I would do it the other way around: Put the always visible text into a custom field per metabox, and protect the post content with a password.
In your theme, always show the custom field, and let WordPress handle the password protection.
Sample code for the theme:
while ( have_posts() )
{
the_post();
if ( post_password_required( $post ) )
{
print '<h1 class="post-protect-notice">' .
__( 'Protected Post', 't5_theme' )
. '</h1>';
the_excerpt();
// custom field
print wpautop(
get_post_meta( get_the_ID(), '_always_visible_content', TRUE )
);
}
else
{
// show regular content
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "conditional content, password"
} |
Paging with category page
I have created my category.php to display all the posts (i am using custom post) in the category.
By default, it's displaying 10 entries, and when i scroll down, i wanna fetch the next 10 entries with jquery infinite scroll. The problem is when i added the following lines to my template, it shows the link(href) to "/category/category_name/page/2" which returns 404.
<?php if($loop->max_num_pages > 1) : ?>
<nav id="page-nav" class="navigation" role="navigation">
<?php previous_posts_link('≪ Previous', $loop->max_num_pages); ?>
<?php next_posts_link('More ≫', $loop->max_num_pages); ?>
</nav>
<?php endif; ?>
How should i set my link (href) so that it fetch the next 10 entries in the same category?
Thank you. | `category.php` is the main category archive template file, which is auto-magically loaded by WordPress for category archives. In that case, use the `pre_get_posts` hook to alter the main query for this page and you shouldn't have trouble with the pagination.
function pregp_wpse_100602($qry) {
if (is_category() && is_main_query()) {
// no idea what conditions you want, but below is a sample
// $qry->set('posts_per_page',5);
}
}
add_action('pre_get_posts','pregp_wpse_100602');
As is, you've created a second loop-- `$loop->`\-- for the page. The pagination functions do not work well when you do that. Those functions depend on the _main_ query, which you are not using. I believe that is the root of the problem.
## Related
Wordpress pagination on custom script
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "paginate links"
} |
wp_trash_post not firing
I want to call a function when a post is placed into the trash. I want to do something more complicated than the following, but have simplified to what's below just to see if it'll work and it doesn't.
function gna_my_function() {
echo 'trashed ';
}
add_action('wp_trash_post', 'gna_my_function');
Thanks | There are two hooks you should be considering-- `wp_trash_post` and `trashed_post`. Based on your statement that you want this to work "when a post is placed into the trash" I'd suggest the latter is the better hook, since it runs _after_ the post is successfully placed in the trash.
I hate to suggest this as an answer but I do think it explains why your function does not appear to output anything. When WordPress saves a post a request is sent to the server, the request is processed, and then the browser is redirected back to the originating page. That means that you cannot always see dumped/`echo`ed output without killing the script. I believe the following should make your apparently debugging function do what you expect it to, provided that you have "trash" enabled.
function gna_my_function() {
echo 'trashed '; die;
}
add_action('wp_trash_post', 'gna_my_function'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "trash"
} |
How to auto send email when publishing a custom post type?
I'd like to have an email automatically sent out to my website's subscribers when I publish a post for a specific custom post type. I've found a few plugins that will do this but only for regular posts (or for any post type that gets published, not allowing you to specify a particular post type). Any suggestions would be greatly appreciated! Thanks. | Hook into `transition_post_status`, fetch the users and send an email to all users.
Sample code, not tested:
add_action( 'transition_post_status', 'send_mails_on_publish', 10, 3 );
function send_mails_on_publish( $new_status, $old_status, $post )
{
if ( 'publish' !== $new_status or 'publish' === $old_status
or 'my_custom_type' !== get_post_type( $post ) )
return;
$subscribers = get_users( array ( 'role' => 'subscriber' ) );
$emails = array ();
foreach ( $subscribers as $subscriber )
$emails[] = $subscriber->user_email;
$body = sprintf( 'Hey there is a new entry!
See <%s>',
get_permalink( $post )
);
wp_mail( $emails, 'New entry!', $body );
}
You should probably use the `Bcc` field. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 2,
"tags": "custom post types, email, subscription"
} |
Approve Page Edits
I'd like to create a role group where users can edit pages and submit them for approval before they are displayed on the website. I've used the following roles (shown below) but they don't allow me to approve page edits. Is it possible to create a role where a user can edit pages and then have the edits be approved by me before being shown on the website?
edit_pages
edit_published_pages
edit_others_pages | I've used the revisionary plugin and it was able to do what I needed. The plugin can be found here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages"
} |
Can I use an array to create multiple tables?
I followed the codex page on how to make tables in the wordpress database with a plugin and was able to understand and get it to work However, the plugin I'm developing has the need for many tables along with joining tables and to code each table individually would be time consuming to say the least.
Is there a way to create a batch of tables using an array() and loop function? | Well, yes, you can build your tables from an array but unless your tables are very similar, and they probably aren't, I don't know that doing that will be any less work than just writing out the definitions. That is, even if you used an array, you'd need to define each table from scratch and then Loop over the array to create the tables. You could save yourself some work, but I doubt it would be very much.
And you seem to be on the right track as far as the WordPress parts of this. That Codex page describes the canonical way to create tables, and you say you have that working.
You can cheat, though, and build your tables in PhpMyAdmin, then dump the definitions :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugin development, table"
} |
Two different pages that share the same content?
I have a self-hosted WordPress site. I need to display the same content on two different pages (a contact page and another page used for promotion purposes).
They will need to have minor tweaks such as a different heading for the H1 and show two different form fields based on the page.
I've used the Advanced Custom Fields plug-in to make it easier for content editors to modify the pages, but I cannot figure out how to just have one place they can go to edit the form fields, sub-text, images, etc. and display this info in two different pages.
Can someone help point me in the right direction? | Have you take a look at Options Page Add-on for Advanced Custom Field? <
I created an option page for my client once where they enter promotion content once in that options page, and display that same information elsewhere via widget, shortcode, and PHP functions.
It costs 25AUD but it's unlimited license and is well worth the price. I bought all of their Add-ons and it saved me a lot of time making client friendly stuff like that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, content, sharing"
} |
How can I connect to another WP database and use WP_Query?
I can connect to the other database with `$db2 = new wpdb( $user, $pass, $db, $host );`, but **how to I get`WP_Query()` to use `$db2`**?
I want to be able to use the loop just the same with `$db2` as I can with the original connection. | `WP_Query` uses the global `$wpdb`. What you'll have to do is replace `$wpdb`, use `WP_Query`, then set it back when you're done.
global $wpdb;
$wpdb_backup = $wpdb;
$wpdb = new wpdb( $user, $pass, $db, $host );
# Do your stuff here...
# then when done...
$wpdb = $wpdb_backup; | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "wp query, wpdb"
} |
How to calculate custom field value (average)
I want to calculate the average value (or other calculation if possible) of several custom field values in a post. For example, I have 4 custom fields in a post, custom1 to custom4, value from 1 to 4 and I want to display the average value. Is there any way to do that? | You can try this to fetch the custom values:
$c1 = get_post_meta( get_the_ID(), 'custom1', TRUE );
$c2 = get_post_meta( get_the_ID(), 'custom2', TRUE );
$c3 = get_post_meta( get_the_ID(), 'custom3', TRUE );
$c4 = get_post_meta( get_the_ID(), 'custom4', TRUE );
Then to calculate the average:
// check if c1, c2, c3 and c4 are all set:
if( strlen($c1) * strlen($c2) * strlen($c3) * strlen($c4) > 0 ){
// convert the values from string to int/float:
$c1 = 1 * $c1;
$c2 = 1 * $c2;
$c3 = 1 * $c3;
$c4 = 1 * $c4;
// calculate the average:
$avg = ($c1 + $c2 + $c3 + $c4) / 4 ;
// output:
// var_dump($avg);
printf( "The average is %.2f", $avg ); // with two decimals:
}else{
echo " missing value! ";
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Get page id by title?
I'm using the following code to insert the content from another wp page into my main home page.
Is it possible to make it work with a page **title** instead of an id number?
Eg. Not $page_id = 518 but $page_id = 'about' instead????
$page_id = 518; //Your Page ID
$page_data = get_page( $page_id );
// Displays the title
echo '<h1>'. $page_data->post_title .'</h1>';
// Displays the content
echo apply_filters('the_content', $page_data->post_content);
?> | There is a function exactly for that:
get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' );
You can use it like this:
$page = get_page_by_title( 'Start' );
To get the page from a specific post type:
$custom = get_page_by_title( 'Start', OBJECT, 'your_custom_post_type' );
$post = get_page_by_title( 'Start', OBJECT, 'post' );
Be aware, this function will search in _all_ post statuses. So you might get a draft, a trashed or private post. You should check the result with:
$status = get_post_status( $page );
if ( 'publish' !== $status )
return; // do not show unpublished posts
A related function is `get_page_by_path()`:
$page = get_page_by_path( 'about/contact' ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "pages, id"
} |
Automatically Assign Parent Terms When A Child Term is Selected
I have deep hierarchical taxonomy and I want to have all parent term assigned when I select a child term. I need it for category structure on a online listing/classified site.
**CPT name:** `product`
**Taxonomy Name:** `product_cat` | Hooking into `save_post` action.
add_action('save_post', 'assign_parent_terms', 10, 2);
function assign_parent_terms($post_id, $post){
if($post->post_type != 'product')
return $post_id;
// get all assigned terms
$terms = wp_get_post_terms($post_id, 'product_cat' );
foreach($terms as $term){
while($term->parent != 0 && !has_term( $term->parent, 'product_cat', $post )){
// move upward until we get to 0 level terms
wp_set_post_terms($post_id, array($term->parent), 'product_cat', true);
$term = get_term($term->parent, 'product_cat');
}
}
}
While loop ensures we go upward until we hit top level terms. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 6,
"tags": "taxonomy, terms"
} |
What's the best way to create a new design for other pages?
I want to create a different design for all new and existing pages, with the exception of the frontpage.
The new design includes another subheader, container, and an extra subfooter.
My guess was to edit footer.php/header.php in my child theme directly, and create seperate subheader/footer/container for these pages, and apply them as follows:
<?php if ( is_home() || is_front_page()){
<div class="subheader_front"></div>
}
else {
<div class="subheader"></div>
} ?>
Is this a correct way of applying a new design, or could this be done simpler? | You can create template files named `front-page.php` and `home.php`, which will be automatically loaded. See the Template Hierarchy for details.
You can also set up different headers for different template files. For instance, if you have a Home Page template `home.php`, you can have a separate header file loaded in it.
In your `home.php` file, you can pass a parameter to your `get_header()` call -- for example, `get_header( 'home' )`. This will look for a file named `header-home.php`, and load it if it exists. Failing that, it will load the default `header.php` file instead. You can do the same with your `get_footer()` and `get_sidebar()` calls.
### Codex Pages
Template Hierarchy
`get_header()`
`get_sidebar()`
`get_footer()` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development"
} |
Add custom attributes to menu items without plugin
I'm trying to figure out the best way to add custom menu attributes without using a plugin. I have a site using a custom theme and need to make sure this is setup at theme activation vs needing to setup a plugin as well.
Is there a function I can plug into for this? | Filter `nav_menu_link_attributes`:
add_filter( 'nav_menu_link_attributes', 'wpse_100726_extra_atts', 10, 3 );
function wpse_100726_extra_atts( $atts, $item, $args )
{
// inspect $item, then …
$atts['custom'] = 'some value';
return $atts;
}
This works with WordPress < 3.6:
add_filter( 'walker_nav_menu_start_el', function( $item ) {
$parts = explode( '>', $item );
$out = array ();
foreach ( $parts as $i => $part )
{
if ( 0 === strpos( $part, '<a ' ) ) // a start
$out[ $i ] = $part . ' data-foo="bar"';
else
$out[ $i ] = $part;
}
return join( '>', $out );
}); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "menus, navigation"
} |
Front-End Interfaces Without Shortcodes
So, I consider myself a "advanced novice" at WordPress development but I still do not have the concept of pages and templates fully understood. I'm having an issue with a feature I'm attempting to include in my plugin and discovered that it's possibly due to the way I am displaying my interfaces on the pages (via shortcodes). Without customizing a theme, how would one display interfaces (grid with interactive functionality) on the font-end? The way my plugin works currently is that it uses shortcodes to house all of my php code that performs the work to display my interfaces and those shortcodes are added as content to pages that my plugin creates upon activation. Is there another way to do this? | What you're doing is, in my opinion, the best way to accomplish this. First off, the pages are a good way to go, because they give users the ability to customize parts of the page like title, meta fields, etc. You don't have to use shortcodes per se, you can filter `the_content` for these pages, but shortcodes offer additional flexibility. For instance, your users can call them directly in a template file if they don't want to use pages, or they can use them in other posts if they want to use a custom post type or something. Anyway, nice work, this is a great way to go. That doesn't solve your issue, but you can probably cross it off your list. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin development, forms, front end"
} |
Problem with $post_id object's property
Dealing with retrieving CPT metadata I find out two methods `get_post_meta()` and `get_post_custom()` to return the value(s) of the custom fields with the specified key from the specified post. Both methods are passing the `$post_id` as first parameter to access global `$post` object's ID property.
Now my question is, how does WordPress figure out which CPT or POST we are asking for? For example at following example how does WordPress understand which post we are talking about
function save_options(){
global $post;
if (!isset($_POST['price']) || $post->post_type != 'product')
{
return $post;
}
update_post_meta($post->ID, "price", $_POST['price']); | I consider this question to be borderline unanswerable. It really depends on context.
In your example `$post` is whatever that `global` has been set to. That is pretty general, pretty obvious, and not really saying much but without knowing the context in which this code executes it is hard to give a better answer.
That variable is set for each post in the Loop by `setup_postdata` or `the_post` and it is set on some back-end pages in similar ways, based ultimately in `$_GET` or `$_POST` data whether that `$_GET` or `$_POST` data contains a post ID or components of a query.
Many of the hooks and filters that you use are passed that value so it is not always necessary to grab the global directly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, metabox, columns"
} |
How to get a localized version of WordPress from a repository?
I'm setting up my basic skeleton / boilerplate I want to use for all wordpress projects. I follow Mark Jaquiths approach and include WP as a submodule. He gets it from < Many of my clients are from Germany and require German language files for administration.
Is there a way I can include the localized files into my skeleton git repository? | > Download your languages files from the SVN repo...
I would strongly advise against this. The repo, as storage of language files, is being discontinued, in favor of Translate WordPress. Right now, you have no guarantees that the repo has a current version of the file.
The current method of getting language files is either to download (export) them directly from Translate WordPress individually (core, admin, network and themes). You can access that directly with something like:
< (for the .mo, replace with format=po for the .po)
Above examples are for core files only, you'd need to repeat that for /wp/dev/admin/de/default, wp/dev/admin/network/de/default, and the themes.
You can "curl" all that, obviously.
We're aware that the method is a little convoluted at the moment, but we're working on a better export tool. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 9,
"tags": "translation, localization, git"
} |
How to turn off automatic operation for Nivo Slider?
I am using Nivo Slider plugin to run a slideshow on my site.
It automatically runs a slideshow on top of my screen. However I want the user to do this _manually_ (clicking to advance to the next slide). How do I turn off the automatic operation? | Have you checked the documentation? It's right in there, in the **jQuery Plugin Usage** section:
$('#slider').nivoSlider({
manualAdvance: false, // Force manual transitions
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, javascript, slideshow"
} |
passing moree than one value of slugs in taxonomy using variable
array(
'taxonomy' => $taxonomy_array_value,
'field' => 'slug',
'terms' => array( $term_name )
)
This is my code where `$taxonomy_array_value` and `$term_name` are variables coming from ajax.
**First Case :**
`$taxonomy_array_value = Colors` and `$term_name = 'red'` then `WP_Query` is working fine.
**Second Case :**
`$taxonomy_array_value = Colors` and `%term_name = 'red','green'` but in this case it's not working.
While instead of using variable if I direct pass 'red','green' in 'terms' then it's working fine but not working with variable Don't know why.
Here is my code from which I am getting $term_name
$term_name = "'" . implode("','", $term_value_array) . "'"; | Try
'terms' => $term_value_array
instead of
'terms' => array( $term_name )
It looks like the problem is that you use `array("'red','green'")` instead of the array structure: `array('red','green')` that you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, wp query"
} |
Too many connections to server
I'm facing a really weird problem with my wordpress/server.
Sometimes when I add media (images) to a new post, and then try to submit this post, instead of my website I got the information in browser:
connection rejected by server
I contacted my hosting provider to solve this problem and they claim that my wordpress is generating too many simultaneous connections to server and that's why my IP is being blocked (usually for about 48 hours). For everyone else the site is working perfectly fine.
Is it possible that adding images/submitting the post is generating more than 18 connections to server (that's the limit that my hosting provider has on its servers)?
And if yes, how to solve this problem?
I'm using wordpress always updated to the newest version. | > I contacted my hosting provider to solve this problem and they claim that my wordpress is generating too many simultaneous connections to server...
The only times I've seen hosts put limits on the number of MySQL connections is when the host is free or very cheap or incompetent.
Is it free hosting? It's really easiest to spend a little money and get a good host.
See Recommended WordPress Web Hosting | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, uploads, media, server"
} |
Add a class to posts in increments of 2
Is it possible to add specific classes to posts/pages in a query in increments of 2?
For example
* Post 1
* Post 2
* Post 3 (add custom class)
* Post 4 (add custom class)
* Post 5
* Post 6
* Post 7 (add custom class)
* Post 8 (add custom class)
* Post 9
I don't mind using jQuery if needs be. | Filter `post_class`, use a static internal counter in the filter callback:
add_filter( 'post_class', 'wpse_100804_post_class' );
function wpse_100804_post_class( $classes )
{
static $counter = 0;
$counter += 1;
switch ( $counter )
{
case 4:
$counter = 0;
case 3:
$classes[] = 'extra';
}
return $classes;
}
In your loop template call `post_class()` like this:
while ( have_posts() )
{
the_post();
?><li <?php post_class(); ?>>
<?php /* more stuff */ ?>
</li>
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, css, query"
} |
Conditionally remove comments and post meta in functions.php
I'm new to Wordpress and am coming from the point and click world of Joomla! what was easy there now involves some solid php knowledge to replicate in Wordpress ;)
I'm try to conditionally remove post-meta and comments from 3 categories using functions.php
I'm using Woothemes Canvas and my own child theme.
I can remove post-meta globally by using an empty function:
function woo_post_meta() {}
This works fine but I only want it to work for 3 categories
I know I need to somehow use is_category butI'm not sure of the syntax, I tried
if ( is_category(4,5,6) ) {
function woo_post_meta() {}
}
but that doesn't work, i'm not sure how to correctly write a function within a function.
Then how do i also remove comments from those categories? or should I make custom content type to do all this? | Here are some ideas:
**a)** Instead of
is_category(4,5,6)
which checks if a category archive page is being displayed (see here), you can try
in_category(4,5,6)
or
in_category( array(4,5,6) )
that checks if the current post is assigned to any of the specified categories (see here).
**b)** You could also try
function woo_post_meta() {
if ( in_category(4,5,6) ) {
return "";
}else{
// the original woo_post_meta() code here.
}
}
**c)** If the original `woo_post_meta()` contains an output filter, than we could add a custom filter with the above category check.
**d)** If you write your own child theme, you could replace the template tag:
woo_post_meta();
with
if ( !in_category(4,5,6) ) {
woo_post_meta();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, child theme, conditional content"
} |
User Meta stuff
Ok I am trying to make a page the list user meta.
<
The part I am stuck on is
`$our_children = get_user_meta ($user_id,"our_children");`
it is a meta field with an array in it.
`a:1:{i:0;a:2:{s:4:"Name";s:6:"Elisha";s:3:"Age";s:2:"13";}}`
How do I display the data in that array?
`//foreach ( $our_children as $children ) { echo '<tr><td>'. $our_children-> Name .'</td><<td>'. $our_children-> Age .'</td></tr>'; //}`
Doesn't seem to work? | You have a few PHP issues preventing output-
1. it appears your foreach is commented out with `//`.
2. you do `foreach( $our_children as $children )`, but then you use `$our_children` instead of `$children` inside the foreach.
3. `$children->Age` is for accessing an object's property, but what you have here is an array, so it should be `$children['Age']`
-
foreach ( $our_children as $children ) {
echo '<tr><td>'. $children['Name'] .'</td><td>'. $children['Age'] .'</td></tr>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, user meta"
} |
Removing h3s in excerpt output?
I have a custom post type and the content looks something like this:
<h3>Description</h3>
The Production Assistant works closely with the production team to ensure that our games ship on time and at our very high standards. You will be a part of an international team and gain valuable insight into game development from a management perspective. Aside from production, you will also expand your knowledge of different disciplines such as, engineering, design, art, human resources, administration, and information technology.
The problem now is that the excerpt outputs something like this now:
<p>Description The Production Assistant</p>
How can I tell WordPress to trim the h3s and the text inside them? | There's a discussion on WP Support Forum that was related to your question. The pastebin constains the function stated in the other answer.
I've decreased the priority to `5` and it works on my test theme.
add_filter( 'get_the_excerpt', 'wp_strip_header_tags', 5);
If you want to target only `<h3>` you can use this regex:
$regex = '#(<h([3])[^>]*>)\s?(.*)?\s?(<\/h\2>)#'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "excerpt"
} |
WooCommerce - how to display product category above product with full details
i'm new in wordpress so please suggest me. i'm selling ring, earings, chains, ect. ring, earings "catogry" and ring-1, ring=2 product. so i want to show on shop page my catogry and on click catogry my products will show | if i'm not totally mistaken you can configure woocommerce that way
-shop
\--category1
\---product1.1
\---product1.2
\--category2
\---product2.1
\---product2.2
without any coding and very easy from your wordpress backend, take a look at:
"woocommerce>settings>catalog" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
change backend header options
Wordpress is offering backend pages for header and background under the design tab, which can be activated inside functions.php.
Is it possible to customize that options? For example I would like to have the possibility to choose a logo.
Or would it be a better idea to not alter that pages and integrate the custom header/background options into my theme's options tabs instead? | I seen lot of Templates using custom theme panels. Giving you separate page into your theme settings will make it easy to find the all the customizations inside one page.
Therefore I will go for a custom panel. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "options, settings api, design"
} |
Get Original Dimension Featured Image on the homepage
I'm trying to integrate a custom slider using a 3rdParty jQuery plugin onto the homepage.
I'm almost there. I need the original featured images and not the cropped ones.
<?php if (is_home()): ?>
<?php
$featured_posts = new WP_Query(array(
'post_type' => 'post',
'showposts' => 5,
'tag' => 'featured'
));
?>
<div>
<?php while($featured_posts->have_posts()): $featured_posts->the_post(); ?>
<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'featured-image'); ?>
<a href='<?php the_permalink(); ?>'>
<img src="<?php echo $image[0]; ?>" style="width:940px;height:500px" />
</a>
<?php endwhile; ?>
</div>
<?php endif ?>
The problem here is that all the images are of 516x340 dimension. How I get the original dimensioned image ? | The second parameter for `wp_get_attachment_image_src` is `$size`.
> `$size`
> (string/array) (optional) Size of the image shown for an image attachment: either a string keyword (thumbnail, medium, large or full) or a 2-item array representing width and height in pixels, e.g. `array(32,32)`. As of Version 2.5, this parameter does not affect the size of media icons, which are always shown at their original size.
>
> <
Per that Codex entry `$size` can take string values of "thumbnail, medium, large or full". You need "full" to get the full size image, which ought to be the original.
It seems to me like you could save yourself a little bit of trouble with `wp_get_attachment_image` instead of `wp_get_attachment_image_src` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
featured image inside post
I want the featured image of a post to display not only in the blog list view, but also inside the post (when i press "Read More..."). How do i do that?
I pasted this
if ( has_post_thumbnail() ) {
the_post_thumbnail('full');
}
in single.php just before the_post();. It looks like this:
while (have_posts()) {
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail('full');
}
the_post();
get_template_part('content', 'single');
}
But the image shows up, above the title. How do i make it show after the title, just like in the blog list view? | @PatJ's answer affords the most control over the placement of the image but involves editing the theme, which may or may not be wise, or possible, depending on the circumstance, so an alternative is to add a filter to `the_content`.
function add_thumb_wpse_100914($content) {
// check that we are on a 'single' post display and...
// check if the post has a Post Thumbnail assigned to it.
if ( is_single() && has_post_thumbnail() ) {
$content = get_the_post_thumbnail(null,'full').$content;
}
return $content;
}
add_filter('the_content','add_thumb_wpse_100914'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post thumbnails"
} |
Front-End Form Submission in Shortcode
The plugin I am working on contains shortcodes with forms on them. Upon form submission (POST), I do some database work, and then planned on redirecting to another page after the db work is complete. When I attempt this, I get the "Headers Already Sent" warning. Within the shortcode function, how do I call my redirect sooner than get_headers? Do I need to use some separate callback function? | You have to hook an earlier action to check if the form was submitted. Something like:
function wpa_process_form(){
if( isset( $_POST['my_form_data'] ) ){
// process form and redirect
}
}
add_action( 'init', 'wpa_process_form' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, shortcode, forms, wp redirect"
} |
can you make changes to a theme in trac while it is waiting for review?
I am wondering if there is a way to make changes to a theme that has been submitted for review and is waiting in trac. I see in this ticket, that it _may_ be possible, but I'm not sure how: <
I noticed a few days after submitting my theme that I had left an extra php file in the folder that isn't needed. < I also notice a minor error in the style sheet - I put the version number in the theme name. I would really like to fix these two issues, just not sure how to go about it.
Should I fix the errors and re-upload the zip file? Will that make the theme loose it's place in line.. It's been 13 days waiting already. | Make the changes and re submit the theme, noting on the old ticket (if you have access to it) that you have submitted a new request with changes. They could reject the theme for any violation of guidelines, so your safest bet is to do this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme review"
} |
Adding new parent item to admin bar
I see many questions have been asked about adding something to the admin bar, but still I can't get a new 'parent' admin-bar item for Advanced Custom Fields to work. The admin bar doesn't show up if I add this to my functions.php:
function my_theme_admin_bar_render() {
$wp_admin_bar->add_menu( array(
'parent' => 'Advanced Custom Fields',
'id' => 'acf',
'title' => __('Advanced Custom Fields'),
'href' => admin_url( 'edit.php?post_type=acf')
) );
}
add_action( 'wp_before_admin_bar_render', 'my_theme_admin_bar_render' );
How can I get this new admin bar item to work? | I don't think you'll need the `parent` for a root menu item while using add_menu. But make sure to get the hint in the Codex:
> Note: The Admin Bar is replaced with the toolbar since WordPress Version 3.3. The preferred way to add items to the toolbar is with add_node().
Give it a try:
add_action( 'admin_bar_menu', 'toolbar_link_to_acf', 999 );
function toolbar_link_to_acf( $wp_admin_bar ) {
$args = array(
'id' => 'acf',
'title' => 'Advanced Custom Fields',
'href' => admin_url('edit.php?post_type=acf'),
'meta' => array('class' => 'toolbar-acf')
);
$wp_admin_bar->add_node($args);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "advanced custom fields, admin bar"
} |
Search through documents folder
Does anyone know why the following returns nothing?
<?php
$dir = get_bloginfo('template_directory') . "/documents/*";
foreach(glob($dir) as $file) {
echo $file;
}
?>
I have files in the documents folder...
Thanks in advance! | `get_bloginfo('template_directory')` returns a URI and I believe `glob` works with paths so try:
$dir = get_theme_root() . "/documents/*";
foreach(glob($dir) as $file) {
echo $file;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, search, pdf"
} |
Show image if author meta (profile fields) exists outside loop
I am trying to show the profile fields (like AIM, Jibber) outside the loop. I managed to do that with
<?php
global $post;
$author_id=$post->post_author;
?>
<?php
$field='aim';
the_author_meta( $field, $author_id );
?>
But now, I can't put an image beside it if such a field exists. This works inside the loop, but not outside:
<?php if (get_the_author_meta('aim')) {
echo "
<div class=schrijver-socialmedia>
<img src= />
"; } ?>
How do I get this image outside the loop and only if the field exists? | `get_the_author_meta` accepts two parameters
* `$field` \- Field name for the data item to be returned.
* `$userID` \- If a user ID is passed to the function, it will return data for the specified user ID.
So just pass the user ID or author ID eg:
if (get_the_author_meta('aim',$author_id)) { ... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, loop, images, user meta, profiles"
} |
Why get_page_template() doesn't show taxonomy template file name?
I made a custom taxonomy called - `work-category` and a template file for it called - `taxonomy-work-category.php`. That part work just fine.
For a purpose I did put `get_page_template()` in that `taxonomy-work-category.php` file to get the current template file name. But it does print out as `page.php` (with full path ofcourse). I was expecting it to print out `taxonomy-work-category.php`.
Even when I'm certain it is printing out from a custom taxonomy template file - Why doesn't `get_page_template()` function doesn't returns the taxonomy template file name? | `get_page_template` returns the template of the current active post/page. You're not on a post/page though, you're in a listing/archive.
When you get `page.php` what you're seeing is the template of the first post/page. The taxonomy listing itself is not a page, it's a listing, and so it makes no sense for it to have a page template, as it is not a page.
See here for an answer that should do what you want:
Get name of the current template file
this may also work:
/* show me what the body class will look like */
echo body_class() . "\n";
/* make sure i've got $template */
global $template;
/* print the active template path and filename */
print_r($template);
( Although why check if you're in template X inside template X, surely the answer will always be yes? ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, templates, taxonomy"
} |
Datetime on time tag wordpress puts it outside the tag
I want to use a time tag with the datetime attribute in it... I tried this in **functions.php** :
<time class="time" datetime='. the_date('d-m-Y') . '>%3$s '.get_the_time( $d, $post ).'</time>'
But instead of putting it in the `time tag`, it outputs the date in the content itself, which is very weird... How can this be solved? | General WordPress rule:
when a function starts with `get`, it will return the value. If it starts with `the`, it echoes the value.
Here, you need `get_the_date('d-m-Y')` instead of `the_date('d-m-Y')`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": -2,
"tags": "tags, seo, date time, html5, timestamp"
} |
Using FlexNav with WordPress
Has anyone managed to get the FlexNav plugin - < \- working with WordPress?
I've got an HTML version of the site working fine, but I'm running into trouble when integrating with WordPress as WordPress uses it's own classes, ids etc. on menu items and this seems to override the flexnav plugin.
I'm wondering if I should be trying to replicate the menu structure that the plugin creates using a custom walker function, or just re-writing the CSS with what WordPress gives me?
Any advice appreciated!
Thanks | You don't need a custom walker function. You can alter wp_nav_menu like this:
wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class' => 'flexnav', //Adding the class for FlexNav
'items_wrap' => '<ul data-breakpoint="800" id="%1$s" class="%2$s">%3$s</ul>', // Adding data-breakpoint for FlexNav
));
and proper script init should be:
jQuery(document).ready(function($){
$(".flexnav").flexNav({
});
});
Drop menu button somewhere outside navigation:
<div class="menu-button">Menu</div>
But still does not work. As toscho refered, FlexNav needs a small modification to work in WordPress. Take a look this mod here <
UPDATE: Since v.1.0 FlexNav support jQuery noConflict mode | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "navigation, responsive"
} |
How do I cleanly override a plugin's CSS with a child theme?
I have taken it upon myself to adhere to WordPress conventions so I can have a clean, sexy child theme. However, I am unsure how to proceed on a certain issue.
I would like to override the CSS for some plugins in my WordPress website, and this wonderful post was a great step in the right direction. My only concern is that I would like to do everything I can to **avoid overriding** the `header.php` file in my parent theme in order the do this.
Is there another wonderful way to do this? Thanks for your help!
**Update** :
As was pointed out by another user's comment, this is in fact dependent on how the plugin implements its styles. This aside, assume that the plugins do provide a way for styles to be implemented in the `style.css` sheet of the child theme, or, in my case, a separate `styles` folder linked to that `style.css` sheet.
I also know I can use `!important` all over the place, but this is generally frowned upon. | If the plugins are correctly adding their styles via `wp_enqueue_style`, you simply need to dequeue them:
function wpa_dequeue_style() {
wp_dequeue_style( 'plugin-style-handle' );
}
add_action( 'wp_enqueue_scripts', 'wpa_dequeue_style', 100 );
Whether or not this works depends on how and where the plugins are adding their styles, so there's no absolute answer without knowing specific methods the plugins in question use.
EDIT- another option that doesn't involve removing the styles entirely is to enqueue your own styles with the plugin styles as a dependency:
wp_enqueue_style(
'my-styles',
get_template_directory_uri() . '/mystyles.css',
array('plugin-style-handle')
); | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 8,
"tags": "plugins, theme development, css, child theme"
} |
Multisite with a single, shared custom post type, while retaining site URL
Small multisite setup, two very different sites, both need to access an `event` custom post type. I don't want to duplicate posts (there are some plugins that "broadcast" a post to the network).
`switch_to_blog(1)` will get me part way there, where `blog 1` is the "master" blog that contains the `event` data, as far as archive-style pages that list all the events. But my concern is that the URL/permalink of the event, when viewed from `blog 2` will point to `blog 1`, and following that permalink will then take the user to the other blog, confusing the user.
Is there a solution (possibly using rewrite) that would allow an event post at `//blog1/events/event1` to appear as `//blog2/events/event1` when viewed from `blog 2`? | There are two options:
1. Register the CPT on blog 2 with `'show_ui' => FALSE`. Hook on blog 1 into `save_post` and copy the data to blog 2.
* Pro: You can search in those posts. Correct templates will be used automatically.
* Con: Duplicated data are always a little bit … dirty.
2. Register an endpoint with an URL scheme like the CPT on blog 1 (`EP_ROOT`).
* Pro: No duplicated data.
* Con: You have to implement the template logic manually to load the correct theme file. And search will not work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, multisite, url rewriting"
} |
Integrating Human Time Difference and Traditional Timestamps?
My goal is to use human_time_diff only when the post was added on the current day. When it wasn't, I would like to revert to the traditional timestamp (the second code). I'm unsure how this would be achieved and need some help. I have provided the two codes I would be combining below.
The code for grabbing the difference between the posting time and current time (i.e. 25 minutes ago):
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>
The code for stating the post was added on X date at X time:
<?php the_time('F j, Y'); ?> at <?php the_time('g:i a'); ?> | You can get the post's creation date/time and compare it to the current date/time.
global $post;
$now = time(); // Current time in seconds since Epoch
$post_created = strtotime( $post->post_date ); // post's creation date in seconds since Epoch, so we're comparing apples to apples
$one_day_in_seconds = 24*60*60;
if ( ( $now - $post_created ) < $one_day_in_seconds ) {
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
} else {
the_time( 'F j, Y \a\t g:i a' );
}
### References
PHP.net:
`time()`
`strtotime()`
Codex:
Post Object (for the `post_date`) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "timestamp"
} |
Open Graph in posts loop page
I have a loop where all the posts have their own like button, when i click it the facebook window appears but it does not show the right post thumbnail. I think this is normal because in a posts loop the thumbnails are multiple so the script can not figure which one goes where - on the contrary the like button works perfectly on my single post pages.
So my question: is it possible to have the facebook like button work correctly on a loop page so that it grabs the right post thumbnail even if there are, say 10 posts in that page?
Maybe i should have multiple Open Graph metas, a set for each post in the loop, but i guess this would just cause a mess, is there something that i can do? | As far as I know this is not possible the way you're trying to get it to work. You can specify an image for Facebook to use in the `<meta>` tag, but that's about it.
One thing you can try is use JavaScript to invoke the Facebook feed dialog. It has a `picture` parameter:
> **picture**
> The URL of a picture attached to this post. The picture must be at least 50px by 50px (though minimum 200px by 200px is preferred) and have a maximum aspect ratio of 3:1
The Javascript Example section at the link above is pretty self-explanatory. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "facebook, open graph"
} |
Removing parent slug from URL on custom post type
As the title states, I'd like to remove parent slugs from URLs for a particular post type: services.
Something that would change this:
etc
To something like this:
etc
I'd rather not use an additional plugins to accomplish this. I'm currently delivering the CPT via a plugin, which also registers a custom taxonomy. | In a quick test, I was surprised to find that this works out of the box. That is, the canonical URI for a child post still has the parent in the path, but the child post works just as well without it (doesn't 404, doesn't redirect). As a result, it should just be a matter of filtering `post_type_link` to get this to work as you're asking! The following code should do just that:
function wpse_101072_flatten_hierarchies( $post_link, $post ) {
if ( 'service' != $post->post_type )
return $post_link;
$uri = '';
foreach ( $post->ancestors as $parent ) {
$uri = get_post( $parent )->post_name . "/" . $uri;
}
return str_replace( $uri, '', $post_link );
}
add_filter( 'post_type_link', 'wpse_101072_flatten_hierarchies', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, permalinks, url rewriting"
} |
Redirect to post with only post ID in the URL vs post_type/post ID
The title may be a little confusing, I don't know how to word it to be short.
Right now my permalink structure is `/%post_id%/%postname%` so the final URL is `/post_type/%post_id%/%postname%`.
When I go to `domain.com/post_id` then it redirects to `domain.com/post_type/%post_id%/%postname%` but when I got to `domain.com/post_type/post_id` it doesn't redirect but shows the correct post.
I'm not sure how to make it work the way the default redirect works. | I used the following plugin lately:
<
to get post ID based shortlinks, like ` That worked very well for me, with a couple of custom post types too.
On a sidenote, I'm not sure about your permalink structure, especially because `%post_id%` and `%postname%` are both uniquely referring to the same post, but on the other hand you might have a good reason for choosing the structure exactly like that.
In reference to Matthew's comment i used the following in my `register_post_type()` call in above mentioned project:
'rewrite' => array( 'slug' => '/%post_type%',
'with_front' => false,
'pages' => true,
'feeds' => '',
'ep_mask' => 1 )
It's just the rewrite part and of course you have to replace `%post_type%` accordingly - I also should mention that the settings for the permalinks would be set to just `%postname%`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, redirect"
} |
Remove old custom field after import
I have imported a set of posts to a new Wordpress install recently. This OLD set of posts had a set of custom fields attached to it (via post_meta using the ACF plugin). The new installation has almost the same fields, with a couple of exceptions. On the posts that have the old (no longer used) custom fields the back-end is still showing those fields when I go to edit the post, even though I do not have them set up in the CURRENT Wordpress installation.
I can only assume this is because the values are in the database (via the import) so Wordpress is displaying them.
How would I go about removing these custom fields and values from the database safely so they do not show up in the post edit screen anymore on the new install? | As far as I know the custom key-value pairs are kept in the `wp_postmeta` table. You can simply examine (and delete) them in the database directly.
SELECT *
FROM wp_postmeta
WHERE meta_key LIKE '%you_old_key_name%'
The ACF configuration of the fields is another story, but you say that you don't even have the field in the new setup, so you shouldn't worry about that one.
Make sure you **backup your database** before modifying or deleting anything, just in case. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "custom field, database, import, advanced custom fields"
} |
How can I make a page for post formats (specifically quotes) in wordpress 3.5
I am trying to create the ability for the end user to add quotes (testimonials) as posts. So far, so good. I have enabled the 'quote' post-format in my theme. So the ability exists to enter said testimonials, and I have even figured out how to show some random quotes in the sidebar. The next obvious step is to have a "testimonials" page, where all of the quotes are archived, over time. It needs the ability to be a page, which means that the client can alter the text in the page, and it can be linked to, in menus and on pages. Following the opening (editable) text, would be a list of the quotes, like an archive page, except that the entire quote would be on the page. For that reason, it would at some point, have to become paged. Any ideas? | Because post formats are a **taxonomy** , WordPress handles the archive index page automatically, using the slug `type` as the taxonomy, and the post format type itself as the taxonomy _term_ ; e.g:
www.example.com/type/quote
If you want to customize the appearance of this **taxonomy archive index** page, you would modify the appropriate taxonomy template file, as per the Template Hierarchy:
* `taxonomy-post_format.php` for _all_ post format types
* `taxonomy-post_format-post-format-quote.php` for the _quote_ post format type. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives, post formats"
} |
Pages not using permalink
I recently changed my theme from one custom theme to another custom theme.
There were previously pages that used template files (i.e., "Blog" page uses Blog template) and now that I've changed themes the pages are not redirecting as usual.
I tried importing the old data and then each page was created twice (i.e., Blog (with permalink blog) and Blog (with permalink blog-2)).
I've tried deleting both pages and choosing to deleted them permanently.
I also tried re-creating the page using the template file (naming it "Blog" with permalink blog), but I continue to get the error:
Index of /blog
Apache Server Port 80
It seems that WP is directing to the folder /blog instead of the page with the permalink blog.
If I change the title of the page (i.e., "Test" with permalink test) and apply the template file the issue resolves. But I would like to keep the same links as the previous design.
.htaccess issue or WordPress issue? | If you're getting
Index of /blog
Apache Server Port 80
instead of a `404` page, you might be having a folder called `blog` in on your server. Try deleting or renaming that folder if you're not using it.
EDIT:
Here is a related question: WP Page and Subdirectory with same name | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, pages"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.