INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Posts not working on windows after changing permalinks
I recently started learning wordpress. Out to curiosity of changing settings, I changed permalinks to Month and Name. After that all my posts and pages have stopped working and show me a 404 Error. I am not being able to figure out why is it happening.
I even tried posting new posts and even they doesnt work.
Please suggest any solution. I am using WP 3.7 on windows machine with wamp. | In wamp you have to manually click/unclick an option to change the .htaccess(and allow permalinks with that).
To do this , click the wamp icon on your (windows) task bar, choose apache > apache modules and check 'rewrite module' | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, 404 error"
} |
Getting a user role from the user login name
The question might be simple. Since I need to fix it soon I had to ask.
Currently I am modifying a free plugin. In that I am having the _user login_ string.
How can I get the role for that login?
I'm using WordPress 3.8. | You'll want to use `get_user_by()`, which will return a `WP_USER` object which contains roles and capabilities. More info here.
$user = get_user_by( 'login', 'username');
$roles = $user->roles // this will contain an array of the roles the user is in | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "user roles"
} |
Passing User_Fields to Contact form 7
I'm trying to pass some custom field data to contact form 7 - The billing address and name and email address.
I've created a function that pulls in these details from the database - is there an easy way I can send these details in an email when a forms sent?
Can I possible somehow pass the data to the form sending template.
Here is my function that pulls in the correct data.
function rinfo() {
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
echo 'Username: ' . $current_user->user_login . "\n";
echo 'User email: ' . $current_user->user_email . "\n";
echo 'Address: ' . $current_user->shipping_address_1 . "\n";
}
} | This plugin helped me solve my question - It pulls in all types of data you just pass the correct key search for "Contact Form 7 Dynamic Text Extension" in the plugin section. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, plugin contact form 7"
} |
Home links redirects to old site
So I have a issue that can´t really wrap my head around, it is most likely .htaccess related. I have just moved my site from a subdirectory to the main directory, this was done changing the site url and the url of the sitebuilder. The new site works fine, but the links to example.se redirects to < this is the way the old site was set up. Now I wonder how to stop this from happening, where I unfortunately removed the old site including its htaccess file. | First back up your database. It is always wise to do that before doing anything. Now download and install Velvet Blues Update URLs plugin. Enter your old URL (like < and new URL (like < and select all options and click Update. Also update your permalinks afterward. This should sort your problem | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess"
} |
search does not yield access restricted results
If the user is logged out and tries to search something, he is redirected to the login page. How is it possible to have the search always show all of the results (including the excerpts and the image), even if the user is logged out and the resulting pages/posts are restricted to members only? I tried using the plugin "WordPress Access Control", but that did not help. | If you setting the posts to private in WordPress, you can add this to your `functions.php` file:
function include_private_in_search( $query ) {
// not an admin page and is the main query
if (!is_admin() && $query->is_main_query()){
$query->set( 'post_status', array ( 'publish', 'private' ) );
}
}
add_action( 'pre_get_posts', 'include_private_in_search' );
Then you can format the search results page to show the excerpt and image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search, user access, membership, logging"
} |
How can I add a column/s to wp_posts table?
I am trying to sync WP with another service that offers an API that allows me to hook up their table's Update, Create, Delete to my sites.
So when they create, update, or delete a row on their server, I get details about that update, including the row ID.
The way I am thinking of syncing is by using custom post types, and either add a new separate table with post -> api relation like `post_id:1 = api_id:53`.
Or alter `wp_posts` table by adding a column containing the api_id.
I know I can add metabox which will add that as post_meta but I am not sure how effective will that be and I am pretty sure if I alter `wp_posts`, querying will be a lot faster.
So how can I alter `wp_posts` in the WordPress way? If that's not possible, should I add meta boxes or create an entirely new table just for the relation ? | You can technically add a post column with SQL but I'd caution against it as backup scripts, exports etc. would likely ignore it.
Instead, I would add the content as a post_meta, either using a Custom Field or through PHP with the update_post_meta() function.
To fetch a post based on the meta simply use:
$args = array(
'post_type' => 'custom_post_type',
'meta_key' => 'api',
'meta_value' => $api_value,
);
$posts = get_posts( $args )
or, to fetch the value of the API key
get_post_meta( $post_ID, 'api', true ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom post types, posts, custom field, metabox"
} |
check if a comment was made by a registered user
Is there any _Conditional Tag_ to check whether a comment is made by registered user or not? | $comment = get_comment( $CommentID );
$commentatorID = $comment->user_id;
if ($commentatorID > 0 ) {
//Comment made by registered user, do stuff
}
From the codex `get_comment()`, about the _return_ value of `user_id`:
> **user_id**
> (integer) The comment author's ID if he is registered (0 otherwise) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "comments, conditional tags"
} |
How to remove custom fields from the selector?
I want to remove some of those:
!enter image description here
So the user doesn't use them by mistake,
Any idea howto? ( maybe looking into the wp database? ) | To hide meta keys from the custom fields form you need to prefix the keys with an underscore, such as `_thumbnail_id`.
To remedy your problem you will need to edit all of the keys in the DB to prefix with an underscore, then you'd need to edit all references in your code. Which is a bit of a pain to do. Perhaps there is a plugin which could help, but not that i know of. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, customization"
} |
How can I create blog specific database table in multisite?
I am creating a plugin, that supposed to work on WP multisite yesterday. I've installed WP multisite on my server. While testing I found out that `register_activation_hook` created 1 table on the main blog only, while I have 2 more blogs.
Here is how I create the tables now:
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$table_name = $wpdb->prefix . "pm_services";
$table = "CREATE TABLE $table_name (
ID bigint(20) NOT NULL AUTO_INCREMENT,
service_id bigint(20) NOT NULL,
name varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY cuunique (`ID`)
);";
dbDelta($table);
Is there a way to creating this table for every blog on the network upon activation ? | The basic process - on activation, check if `is_multisite`, get all of the sites with `wp_get_sites`, loop over the results with `foreach` and `switch_to_blog` for each site ID, and create the table.
You'll also need to hook the `wpmu_new_blog` action, check if `is_plugin_active_for_network`, switch to that blog ID and run your activation code, so sites added after activation have their table created. Don't forget to switch back to the original blog ID after you run your activation. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "multisite, database, activation"
} |
How to change the markup created by menu item only on chosen items?
How to add a checkbox to the menu item in WordPress backend that says "Make this a Mega Menu Container"? In my mind it should look something like this (Photoshop draft): !enter image description here
And when the box is checked instead of adding another standard ul > li DOM element a div container is added instead?
I have no idea how to approach this. I was planning to use walker to change the DOM for the menu, but how to "activate" the walker only for some menus - in this case the menus that I choose by that checkbox to be the mega menu? | OK this one is solved. I actually created a separate items that can be dragged in as a link, but are actually hard coded pieces of markup with adequate classes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "menus, admin, html"
} |
Letting users create a post that is a custom post type from a page
I'm trying to create a kind of "Request for Proposals" system for a blog that belongs to a client of mine.
I'm not too sure how to go about this, but so far I've outlined this much..
I know there will be two kinds of users for this. 1\. Proposers 2\. Speculators
Proposers will be able to submit their proposals from the front-end of the site.
Speculators will be able to login and see the page that lists all the most recent proposals, as well as view them individually. Speculators should be the only role allowed to do this.
Now, I'm having a hard time figuring out how to create these two user types.
I can see in Press Permit videos that he's got user roles like "Student" and a few others. But there isn't any video that shows how he was able to create those users. | You can create a new role and name it anything you like.
Then you can add any type of capability you like
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user roles"
} |
SEO implications of assigning a new domain to a multisite subdomain
I run Wordpress in Network mode (subdomain), and I have built up a good page rank for one of my subdomain sites.
If I register a proper domain name for my network subdomain site, and use the domain mapping plugin to take it from a subdomain of the first site, to being a new domain, does Wordpress do a 301 redirect from the subdomain of the first site to my new domain?
Thanks. | In the "Domain Mapping" section of the WordPress MU Domain Mapping plugin (found under Settings in Network Admin), there is a check box to turn on and off the "Permanent Redirect", which is a 301 permanent redirect. Turning it off effects a 302 temporary redirect. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, seo"
} |
get custom post type categories
From <
$categories = get_categories( $args );
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
I thought that 'type' was the post type. But not. This is the type of category to retrieve. I've researched without success.
So, any idea of how to retrieve all categories assigned to all post of specific post type? | A brute force solution that works for any post-taxonomy relationship:
global $wpdb;
// set the target relationship here
$post_type = 'post';
$taxonomy = 'category';
$terms_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT
tt.term_id
FROM
{$wpdb->term_relationships} tr,
{$wpdb->term_taxonomy} tt,
{$wpdb->posts} p
WHERE 1=1
AND tr.object_id = p.id
AND p.post_type = '%s'
AND p.post_status = 'publish'
AND tr.term_taxonomy_id = tt.term_taxonomy_id
AND tt.taxonomy ='%s'
", $post_type, $taxonomy ) );
// here you are
$terms = get_terms( $taxonomy, array(
'include' => $terms_ids,
'orderby' => 'name',
'order' => 'ASC'
) ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, categories"
} |
Menu id in nav menu ignored
<?php
wp_nav_menu(
array(
'theme_location' =>'main_menu',
'container' => false,
'menu_id'=> 'nav'
)
);
?>
After updating WordPress to 3.8 menu id is not working. Where is the problem ? I like to get menu as
<ul id="nav">
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
</ul> | Try replacing `'menu_id'=> 'nav'` by `'items_wrap' => '<ul id="nav">%3$s</ul>'` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
How to use wordpress content class?
<div class="sidebar_area">
<h4>Sponsor</h4>
<div class="sidebar_content">
<ul>
<li><a href="#">This is new post</a></li>
<li><a href="#">This is new post</a></li>
<li><a href="#">This is new post</a></li>
<li><a href="#">This is new post</a></li>
<li><a href="#">This is new post</a></li>
<li><a href="#">This is new post</a></li>
</ul>
</div>
I like to make my widget like this code. But problem is here I can't use widget content like bellow. How can I give sidebar content div with "sidebar_area" class.
<div class="sidebar_area">
<h4>Sponsor</h4>
<div class="sidebar_content">
<!-- content goes here -->
</div> | If I understood you correctly, this is what you are trying to achieve:
register_sidebar(array(
'name' => 'Sidebar Name',
'id' => 'sidebar-id',
'before_widget' => '<div class="sidebar_area">',
'before_title' => '<h4>',
'after_title' => '</h4><div class="sidebar_content">',
'after_widget' => '</div></div>',
));
**References:**
* `register_sidebar` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets"
} |
So strange result of wp_query and have_posts
I've tested some piece of simple code, but the result is so so strange.
**Test 1:**
$featured_posts = new WP_Query( $query_args );
while ($featured_posts->have_posts()) {
$featured_posts->the_post();
the_title(); echo '<br>';
}
echo 'End: "' . $featured_posts->have_posts() . '"'; // have_post() is TRUE, WHY?
**Test 2:**
$featured_posts = new WP_Query( $query_args );
$have_posts = $featured_posts->have_posts();
while ($have_posts) {
$featured_posts->the_post();
the_title(); echo '<br>';
$have_posts = $featured_posts->have_posts();
}
echo 'End: "' . $have_posts . '"'; // false -> I think false is right.
echo 'End: "' . $featured_posts->have_posts() . '"'; // but still TRUE, WHY?
Am I missing anything? | If we look at `have_posts()` in source, we can see why this happens:
function have_posts() {
if ( $this->current_post + 1 < $this->post_count ) {
return true;
} elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
do_action_ref_array('loop_end', array(&$this));
// Do some cleaning up after the loop
$this->rewind_posts();
}
$this->in_the_loop = false;
return false;
}
When it reaches the end of the loop, it calls `rewind_posts`, which resets `current_post` back to `-1`, so the next call to `have_posts` will return true again.
function rewind_posts() {
$this->current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp query"
} |
Adding Page Ordering to a Custom Page Type
I've created a custom page type (that is, a custom post type converted to a page). This template is used to display profiles of employees.
I then use the Simple Page Ordering plugin to order my pages and staff profiles in the custom page template. It works well for my normal pages but isn't working for my custom page template.
I'm not sure what I need to do to make the page ordering work. I noticed my custom page template doesn't have ordering on the edit screen and I'm unsure how to add it - perhaps that would do it?
Here's my archive template markup for my custom pages: <
Full functions (in functions.php) for the custom page template: < | The simple page ordering plugin works by using the `menu_order` setting in the `order_by` settings of a query. Check it out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, order"
} |
jQuery code didn't run on my plugin
I use this to hook my scripts and styles to my plugin:
add_action('admin_init', 'the_box_init' );
// Init plugin options to white list our options
function the_box_init(){
register_setting( 'the_box_options', 'the_box', 'the_box_validate' );
wp_enqueue_style( 'myprefix-style', plugins_url('theboxstyle.css', __FILE__) );
wp_enqueue_script( 'myprefix-script', plugins_url('theboxjs.js', __FILE__) ); //this hook my custom js, preferrably which contents almost my jquery codes.
}
However, the jQuery code doesn't work; even this simple code:
$( document ).ready(function() {
alert("asdasd");
});
Only plain JavaScript did work.
What do you suppose went wrong in my implementation that jQuery doesn't work?
I'm open to any suggestions, recommendations and ideas. | Check the DOM for the theboxjs.js and see if it is loaded correctly (check the output path). If not then you have path issues.
Try using `admin_enqueue_scripts` instead of `admin_init` for loading scripts.
You might also have conflict in your script. When writing scripts for WP try to avoid `$` and use `jQuery` instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, jquery"
} |
How To Remove WordPress Version From The Admin Footer
Is there anyway to remove version number from the right side of WordPress admin footer?
I know this code will add some text before the version number, but it will not remove it:
function change_footer_version() {
echo 'Anything';
}
add_filter( 'update_footer', 'change_footer_version', 9999 );
And the following code will do nothing:
function change_footer_version() {
return ' ';
}
add_filter( 'update_footer', 'change_footer_version', 9999 );
So, is there anyway to remove the entire `<div>` from the template or anything with `functions.php` file? | Add this to your `functions.php`:
function my_footer_shh() {
remove_filter( 'update_footer', 'core_update_footer' );
}
add_action( 'admin_menu', 'my_footer_shh' );
or, if you'd like to hide it from everyone except admins:
function my_footer_shh() {
if ( ! current_user_can('manage_options') ) { // 'update_core' may be more appropriate
remove_filter( 'update_footer', 'core_update_footer' );
}
}
add_action( 'admin_menu', 'my_footer_shh' ); | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 10,
"tags": "admin, wp admin, footer"
} |
Post dynamic fields and style
dynm!Desired Post style
I am stuck in getting wordpress post to the attached screnshot's style, My apology for being a pretty noobs amd my question shows it. I searched and found a wonderful article : how-to-display-word-count-of-wordpress-posts-without-a-plugin Most of my desired features are figured out there very well but still looking for a way to input price field, can I have a price field while posting from admin panel ? | Just use a custom field. On post or page edit page click **Screen Options** in the top right corner anb select _Custom Fields_. Add a Name and Value pair for example: price (for the name) and 9$ (for the value).
Then in your single.php or whatever template use this code to display it:
<?php echo "Price:" . get_post_meta($post->ID, "price", true); ?>
**Reference:** get_post_meta | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts"
} |
Overview with latest edited posts and pages
I'm looking for an overview of all the latest user activities.
But I don't want to see comments on this page, just the edits or creations of new posts or pages.
Unfortunately I can't find such a page on our installation. Could you help me out? | You can use the $WPDB query to query the DB, an example would be:
$editedposts = $wpdb->get_results(
"
SELECT ID, post_title
FROM $wpdb->posts
WHERE post_modified = between DateAdd(DD,-7,GETDATE() ) and GETDATE()
"
);
This lists all posts which have been edited in the last 7 days (not tested), you would do something similar to get posts created in that date:
$newposts = $wpdb->get_results(
"
SELECT ID, post_title
FROM $wpdb->posts
WHERE post_date = between DateAdd(DD,-7,GETDATE() ) and GETDATE()
"
);
You can then query the data using the variable e.g.
foreach ( $editedposts as $newposts ) {
echo $newposts->post_title;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages, admin, users"
} |
Pull Custom /wp-admin/css for Non-Admin in Multisite
Here's a problem I'm sure many would like to find an answer to...
In a multi-site install, sometimes I would like blog owners to have their dashboard display differently style-wise. These styles are largely controlled by the /wp-admin/css/ folder.
The problem is that if we edit /wp-admin/css/, it impacts everybody - the MultiSite administrator included.
Is there a way to pull a custom /wp-admin/css/ folder for all site users other than the site owner? Thus allowing the site owner to still see the traditional panel and everybody else with a site inside the network to see a custom designed one controlled by stylesheets in /wp-admin/css/. | Something like the following should work:
global $blog_id;
if ($blog_id == 1) {
wp_enqueue_style(
'custom-style',
'/wp-content/css/new_styles.css'
);
}
Basically it checks if the person is on blog_id 1 and then loads the respective CSS from the CSS folder (you would need to create this).
This would go in your functions.php | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "multisite"
} |
Custom Post Type Posts Not Showing Up in Admin
I am using this theme called IronBand. It has a few custom post types, and one of them is called "Gig."
I created some custom posts under that Custom Post Type. Later, I wanted to changed the name of the Custom Post Type to "Show," so I fiddled with some php files. It seemed like it was too complicated to change everything accordingly, so I replaced the php files I fiddled with to the original php files.
Now in the admin panel of "Gig," it says "No Gigs Found" Even if above the post list it says there are 17 published posts. How could I make the published posts show up again? | When you fiddled, it's possible that your custom posts were created with your "Shows" post type, not "Gig".
You could check that in the database directly using PHPMyAdmin or whichever tool your host offers.
In PHPMyAdmin look for your wp_posts (the wp_ could be different) and look at all of the posts probably clicking on the ID column to sort the newest to the top, then scroll to the right and look for the post_type column of a row that contains one of your test posts.
It's not ideal, but you can now delete those posts (you should also find the posts_meta for them), or change the post_type column. Or just leave them alone and they shouldn't cause you any trouble. Unless you create another post type called Shows which could bring them back. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Buddypress Group Activity Loop Filter activity type
I'm using Buddypress 1.8.1
When the group home page load I want to show only 'activity_update' and 'joined_group' activities in Activity Loop.
Here is my Activity Loop code. It is standard loop code.
<?php if ( bp_has_activities( bp_ajax_querystring( 'activity' ) ) ) : ?>
<?php while ( bp_activities() ) : bp_the_activity(); ?>
<?php locate_template( array( 'activity/entry.php' ), true, false ); ?>
<?php endwhile; ?>
<?php endif; ?>
How to filter these activities in page load. Thanks. | I have created this function in bp-custom.php page.
function filtering_activity_default( $query ) {
if ( empty( $query ) && empty( $_POST ) ) {
$query = 'action=activity_update,joined_group';
}
return $query;
}
add_filter( 'bp_ajax_querystring', 'filtering_activity_default', 999 );
This is working for me as expected. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, filters, buddypress"
} |
How to create a non-responsive WordPress Theme Using Genesis Framework?
I am new to coding and I really don't know how to create a non-responsive child theme which runs on the Genesis framework. Besides that, I tried to modify a child theme and it all went well but one day when i tried to re-size the browser window i noticed that the theme was all messed up and looked ugly. I really want to know whether it is possible to remove the responsiveness from a Genesis child theme or not. | You can remove all the CSS code under the Media Queries section of any child theme built on Genesis. This code is generally located at the end of the style.css file.
However, WordPress also includes responsiveness built in so its not really possible to totally remove everything unless you go to a lot of trouble.
If you remove all the Media Queries, you will find your site will not look good when re-sized so its not a good idea to remove any CSS. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "child theme, genesis theme framework, responsive, remote, customization"
} |
Specifying a size when displaying an image associated with a taxonomy through ACF
I created a "books" custom taxonomy for my "book" CPT. Using ACF, I assigned an image to each my custom taxonomy terms.
I have a page where I display all my "books" terms as images. It works but now I want to specify a particular size to these images. The code of the page:
<?php
$taxonomy = 'books';
$tax_terms = get_terms($taxonomy);
?>
<ul>
<?php
foreach ($tax_terms as $tax_terms) {
$taxonomy_image = get_field( 'taxonomy_image', 'books_'.$tax_terms->term_id );
$taxonomy_image_url = $taxonomy_image['url'];
?>
<img src="<?php echo $taxonomy_image_url; ?>" alt="" />
<?php
}
?>
</ul>
I think the ACF doc page about images contains the key to what I'm trying to do - especially the part about image size, but I can't seem to find a way to integrate it to my code successfully. Any suggestion? | It appears you currently have the field set to return the image object, if you scroll down to the bottom of the page you linked you'll see an example object:
Array
(
[id] => 540
[alt] => A Movie
[title] => Movie Poster: UP
[caption] => sweet image
[description] => a man and a baloon
[url] =>
[sizes] => Array
(
[thumbnail] =>
[medium] =>
[large] =>
[post-thumbnail] =>
[large-feature] =>
[small-feature] =>
)
)
so for a specific size you want to replace `$taxonomy_image['url']` with `$taxonomy_image['sizes']['thumbnail']`, where `thumbnail` is the desired size key. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, advanced custom fields"
} |
WP_Query Limit Data_Query last 90 days
I want to perform a `WP_Query` that finds all posts limited to the last 90 days. From my understanding, WP_Query accepts numerical values for months, years, days, etc, but I'm not sure I understand how to pass an argument that says "get all posts from 90 days ago until today."
I'm guessing I have to get the current time and then subtract 90 days from that, but it looks like the "day" argument is relative to the month (i.e. 1-31). There is no way to compare timestamps?
This is sort of what I have so far -
$today = getdate();
'date_query' => array(
array(
'day' => array( $today["day"], $today["day"] - 90 ),
'compare' => 'BETWEEN',
)
) | In order to query posts with a `date_query`, you can pass the argument of column `post_date_gmt` which is the date the post was published, and then pass the argument of `before/after` and a string to represent your request. So for published posts from now until 90 days ago, you would put this in your `WP_Query` args:
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '90 days ago',
)
)
This says get me all posts from 90 days ago and AFTER, which would stop at present time.
You could pass the string `3 months ago`, `1 year ago`, etc. It basically takes on the same behavior of `strtotime()`. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 0,
"tags": "wp query"
} |
What hook can I use to modify custom post data before it is displayed on the page?
I need to check if a certain value is true in the post_meta right after the wp fetches a custom post from database, If it's false I need to modify/add some data to the post and then display the modified version, if it's true it should continue as usual. What would be the best hook and approach in general to accomplish something like this?
Edit: Forgot to mention before, but I would HIGHLY prefer to do this inside a plugin. | You can use `the_content` filter to modify content before it's output.
function my_the_content_filter( $content ) {
// maybe limit to archive or single cpt display?
if( is_post_type_archive( 'your-cpt' )
|| is_singular( 'your-cpt' ) ){
global $post;
$meta = get_post_meta( $post->ID, 'some-key', true );
if( false === $meta ){
return $content . 'some extra content';
}
}
return $content;
}
add_filter( 'the_content', 'my_the_content_filter' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, custom post types, posts, hooks, actions"
} |
WPSC how do i output product per category on one page (wpsc-product-page)
I am trying to output and sort products per category, like:
Cat1
prod
prod
Cat2
prod
Cat3
prod
prod
prod
I am able to get the cat_ID per product, but how do i display
<?php while (wpsc_have_products()) : wpsc_the_product(); ?>
<?php
$wpsc_product_category = get_the_product_category( wpsc_the_product_id() );
$curr_cat = $wpsc_product_category[0]->name;
$cat_id = $wpsc_product_category[0]->cat_ID;
//print_r( $wpsc_product_category);
echo $cat_id;
?>
Any tips, suggestions? | You need to do 2 queries, 1 for the terms (using get_terms) and then a post query, an example is:
$taxonomy = 'portfolio_types';
$tax_terms = get_terms($taxonomy);
foreach ($tax_terms as $tax_term) {
echo '<li>' . '<a href="#'.$tax_term->slug.'"' . '>' . $tax_term->name.'</a></li>';
}
endwhile; endif;
wp_reset_query();
$the_query = new WP_Query( 'post_type=portfolio&portfolio_types='$taxonomy );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_title();
endwhile;
You will need to change the post_type and the taxonomy to yours (not tested though)
Basically what the script does is find all the taxonomy terms, and when it finds one it looks for any posts under that term. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin wp e commerce"
} |
Order get_users() by last login date. Is it possible?
I want to create a page that displays all the blog users ordered by the last login date.
I've tried with the get_users() function and I can succesfully get the users' list, but not in the order I want:
$query = get_users('&offset='.$offset.'&orderby=login&order=DESC&number='.$number);
I think that the orderby=login is not what I'm looking for... Is there any other way to accomplish this? | First, you need to store the actual login date, because this is not stored by default. You can use this code to do that(use it in your functions.php)
add_action('wp_login','user_last_login', 0, 2);
function user_last_login($login, $user) {
$user = get_user_by('login',$login);
$now = time();
update_usermeta( $user->ID, 'user_last_login', $now );
}
After that, you can use the meta field to sort the results:
$query = get_users('&offset='.$offset.'&orderby=meta_value&meta_key=user_last_login&order=DESC&number='.$number); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "functions, order, users"
} |
fire action when post is being edited as well as saved?
I'm trying to fire some code when a page is edited and/or saved. This code works:
add_action( 'save_post', 'add_promoted_meta_data' );
function add_promoted_meta_data( $post_id ) {
echo '<h1>test</h1>';
}
...but this code does not:
add_action( 'edit_post', 'add_promoted_meta_data' );
function add_promoted_meta_data( $post_id ) {
echo '<h1>test</h1>';
}
What action would I use to combine the functionality? I ultimately need to fire code upon creating or editing a post?
Thanks in advance! | The documentation for the `save_post` action says:
> `save_post` is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email.
So, you should only need the `save_post` action to run the desired code when the post is changed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, functions, hooks"
} |
How do I embed an image at actual size?
I'd like to give the user the option to insert images into posts, and have the image display at its actual size.
How do I do this?
Currently, if an image is selected from the media library, a dropdown menu displays, giving sizing options. None of the options allow for a default size.
Neither are there any options that allow for inline style to be turned off for the image. | Under ATTACHMENT DISPLAY SETTINGS > Size > Select Full Size from the drop down menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, media library, wysiwyg"
} |
Wordpress Custom Query to show posts from last x years
I have found a way to show all posts from the current year with this code:
<?php
$today = getdate();
$lastyear = $today[ 'year' ];
$args = array(
//'nopaging' => true,
'paged' => $paged,
'category' => 1,
'posts_per_page' => 36,
'year' => $lastyear,
);
query_posts( $args ); // The Query ?>
<div id="grid">
<?php while ( have_posts() ) : the_post(); // The Loop ?>
<?php get_template_part( 'article', 'thumb' ); ?>
<?php endwhile; ?>
</div>
<?php get_template_part( 'navigation' ); ?>
<?php wp_reset_query(); // Reset Query ?>
However, what I really want is to show posts from 2 years ago till today (it's Jan 2014), meaning, posts from 2012 and 2013 and 2014. How do I do this?
Many thanks in advance. | <?php
$today = getdate();
$args = array(
//'nopaging' => true,
'paged' => $paged,
'category' => 1,
'posts_per_page' => 36,
'date_query' => array(
array(
'after' => $today[ 'month' ] . ' 1st, ' . ($today[ 'year' ] - 2)
)
)
);
$catgory_posts = new WP_Query( $args ); // The Query ?>
<div id="grid">
<?php if( $catgory_posts->have_posts() ) while ( $catgory_posts->have_posts() ) : $catgory_posts->the_post(); // The Loop ?>
<?php get_template_part( 'article', 'thumb' ); ?>
<?php endwhile; ?>
</div>
<?php get_template_part( 'navigation' ); ?>
See date parameters at WordPress codex: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "wp query, loop, query posts, date, date time"
} |
Adding a class to tag list in a function
How can I add a class to the function so I can style the output tags as boxes in css?
<?php
if(get_the_tag_list()) {
echo get_the_tag_list('<ul><li>','</li><li>','</li></ul>');
}
?> | If you are passing the `before` parameter that you can simply add any class that you want. You then style that class in `style.css`.
<?php
if ( get_the_tag_list() ) {
echo get_the_tag_list('<ul class="tag-list"><li class="tag-item">','</li><li class="tag-item">','</li></ul>');
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "functions, taxonomy, tags"
} |
Custom Field select list is truncated
The site I'm working on has many custom fields being used in it's pages. For some reason though, the list of custom fields that you can pick from the dropdown only displays the first 30 field names.
If I want to use an existing custom field that isn't, alphabetically, in the first 30, I have to manually type it in each time.
Any idea why? | As explained here there is a WordPress limit of 30 for the number of custom fields that are available by default. But you can change the behavior as shown with the hook `postmeta_form_limit` in the below example.
add_filter( 'postmeta_form_limit' , 'customfield_limit_increase' );
function customfield_limit_increase( $limit ) {
$limit = 100;
return $limit;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, pages, wp admin"
} |
How to add class on term link?
I am looking for a way to add tag slug as a class. I can't figure out how to achieve this...
Here is how I display the products tags
`<?php echo get_the_term_list( $post->id, 'product_tag'); ?>`
The output is
`<a href=" rel="tag">My tag</a>`
And I want
`<a href=" class="Tag_Slug" rel="tag">My tag</a>` | I think you should use a custom loop:
<?php
$terms = get_the_terms( $post->ID, 'product_tag' );
if ($terms && ! is_wp_error($terms)): ?>
<?php foreach($terms as $term): ?>
<a href="<?php echo get_term_link( $term->slug, 'product_tag'); ?>" rel="tag" class="<?php echo $term->slug; ?>"><?php echo $term->name; ?></a>
<?php endforeach; ?>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "tags, terms"
} |
Where is dynamic_sidebar content defined?
A friend has asked me to edit a WordPress site that someone else has made for them. Part of it contains the following code:
dynamic_sidebar('footer4')
Which spews out a contact form.
What I want to know is, is there an easy way for me to find out where the function that returns the HTML this contact form is defined?
For example, if there was actually a function called 'footer4', I could do this:
// I've tried this and it doesn't exist;)
$reflFunc = new ReflectionFunction('footer4');
print $reflFunc->getFileName() . ':' . $reflFunc->getStartLine();
I've looked through all the template files and couldn't see anything.
Any advice appreciated. | Just check **Apperances>Widgets** Under **footer4** inside text you can find the HTML form you need to edit. You can find more in Function Reference/dynamic sidebar | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "sidebar"
} |
Add feed to a custom page
I have searched and found a lot of people asking about how to add a custom rss feed for custom post types/taxonomies. However that's not the problem right now.
I have 2 extra pages on my site that looks like the default index page (with loop and stuff), the only difference is that they have a different orderby. And I want a feed for those pages too. Putting /feed behind those pages returns a Comments feed with no items. How come? The code of those pages are almost identical to index.php and the feed link works fine there.
I understand there's a add_feed function. But I don't want a new feed type, just the default one is fine. | MikeNGarret's answer might work, I did not understand it though so I went with an alternative apporach. What I did was make a blank new page template instead, and coded it like a RSS/XML page with my new query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, rss, feed"
} |
ACF: Display category name using taxonomy field
I'm currently using the taxonomy field in ACF, with the aim of printing the category name in the front end. Using it like so:
<?php $term = get_sub_field('category_selector'); if( $term ): ?>
<span><?php echo $term->name; ?></span>
<?php endif; ?>
Which is currently displaying nothing, I've debugged the `$term` which doesn't display the category ID of `3`, but for some reason I can't get hold of the category name from this? Any suggestions would be greatly appreciated! | Assuming that `3` is a category ID...
$term = get_sub_field('category_selector');
if( $term ) {
foreach($term as $t) {
$t = get_category($t);
echo $t->name;
}
}
In other words, it looks like ACF is just storing the ID, not the whole object, so you need to use that ID to grab the category object before you have access to the name, slug, etc. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, taxonomy, advanced custom fields"
} |
Return category posts with WP_Query
I have a some categories and want to get the posts with those categories:
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query('cat=85');
if($wp_query->have_posts()) {
...
}
But it is not entering in the `if` condition. The category with `id=85` exists and some posts are using it. So I don't understand why it is not returning any post.
Any idea. Am I doing something wrong? | By default `WP_Query` will return only the `post` post type. To retrieve other post types, you need to add a `post_type` argument. Using `any` will return results from all public, registered post types.
$my_query = new WP_Query(
array(
'cat' => 1,
'post_type' => 'any'
)
);
var_dump($my_query->request); // debug; allows you to see the SQL
if($my_query->have_posts()) {
// ..
}
If you only want a particular post type, just use the post type's slug, or you can use an array of post type slugs to get returns from multiple particular post types.
Also, there is rarely a good reason to clobber `$wp_query`, even if you save it to put it back later. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, wp query"
} |
Changing permalink settings causes 404
I would like to have permalinks of the form ` I tried to achieve this by changing the permalink settings in the admin panel to 'Post name' from default. But this causes 404: page not found error.
I've tried with the other settings e.g., month and name, numeric etc. but all of them results in 404. The generated URL is changing according to the permalink setting though.
Clearing the cache did not help either.
Does something else need doing here ? Thanks.
Edit:
My server: lamp on ubuntu 12.4 lts
Contents of the .htaccess
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /mysite/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /mysite/index.php [L]
</IfModule>
# END WordPress | There are several possibilities: you may need to enable mod_rewrite on the Ubuntu server or check/fix permissions to allow Wordpress to write to the .htaccess file.
Best thing to do is read < and work through suggestions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, 404 error"
} |
Is there a filter for get_post_custom()?
I know there's a filter get_post_content that I can hook into, but that only seems to work with get_post_meta, I need to filter individual values of get_post_custom() by checking if the metadata key matches like:
function filter_custom($meta)
{
foreach($meta as $k => $v)
{
if ($k === 'some_key') return $v . 'filtered';
}
}
add_filter('get_post_custom', 'filter_custom');
Is there a hook for this? if not what would be the best way to accomplish it? | The quickest way to answer this question is to follow the code. See `get_post_custom` in Codex. Scroll down to **Source Code** section:
> get_post_custom() is located in wp-includes/post.php
There we'll see that `get_post_custom` calls `get_post_meta`, which then calls `get_metadata`, which points us to:
> get_metadata() is located in wp-includes/meta.php
there we'll finally see the available filter:
$check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
in this case, `post` is the `$meta_type`, so our filter is `get_post_metadata` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, filters, post meta"
} |
get_option('sticky_posts') returns stickies that are in trash
The value of get_option('sticky_posts') includes those that are in the trash. How can I get a value minus stickies that are in the trash?
var $stickies = count(get_option('sticky_posts')); | Why is that even happening aside, from quick look at core it does the following to achieve that in `WP_Posts_List_Table` class:
$sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) );
$this->sticky_posts_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ('trash', 'auto-draft') AND ID IN ($sticky_posts)", $post_type ) ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sticky post, trash"
} |
Syling Custom Fields echo's from from functions.php
With the help of User Borek I've managed to get Custom Fields displaying on my siteby putting the below in the functions.php:
function custom_field_before_content() {
if(is_page() || is_single() || is_archive() ) {
echo genesis_get_custom_field('instrument');}
}
add_action( 'genesis_entry_header', 'custom_field_before_content' );
I'm having trouble putting an id or class on them though so I can style them. I am using a Genesis theme and I can't figure out how to do this. I have tried following this tutorial with no success. Does anyone know where I can put an id or class on these custom fields in a genesis theme?
This is one of the pages where my custom fields are displaying: < Right above the image and under the title.
Appreciate any help,
Ciarán | How about just echoing out the needed syntax like that:
echo '<div class="custom-field">' . genesis_get_custom_field('instrument') . '</div>';
You can also just use CSS and style the
header.entry-header {
//your sexy styles goes here
}
Since other elements inside are wrapped in their own elements and styled separately (I mean the actual H1 and meta data) the only altered item will be the bare custom field value. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, custom field, id, genesis theme framework, css"
} |
the_excerpt() does not work with has_excerpt()?
I'm trying to shorten the excerpt but it does not work. It shows the full excerpt which I write in the post edit!
I've added this to the functions.php
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
To show the excerpt I'm using in content.php:
`if(has_excerpt()) { the_excerpt(); } else { the_content(); }`
The above code display full excerpt, not shortened!
Without `has_excerpt()` `if statement` it displays correctly.
Where can be the problem? Any ideas what can cause this? | `excerpt_length` is only applied to generated excerpts\-- excerpts automatically generated from the post body.
To trim your manually created excerpt, use the same function that trims the generated one\-- `wp_trim_words`.
if(has_excerpt()) {
$length = apply_filters('excerpt_length',20);
echo wp_trim_words(get_the_excerpt(),$length);
} else {
the_content();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, excerpt"
} |
Filter or action hook to insert content on admin pages before </body> tag
I am developing an administrator plugin and want to be able to write some HTML content just before the last body tag . This content will initially be hidden then displayed with javascript when a user clicks on a button.
Can anybody advise if there are any action or filter hooks that I can leverage to insert this? Remember this is for admin pages not theme pages. | You can use the `admin_footer`, `admin_footer-(hookname)` or `admin_footer-(plugin_page)` actions. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugins, filters, admin, hooks, actions"
} |
Custom Post Type - Archive page title
I'm wondering if I could make a custom _Page_ title for my Custom Post Type _Archive_ page? Right now I'm using:
<title><?php wp_title( '|', true, 'right' ); ?></title>
For my regular pages, it display what I want, but on my custom post type archive page it displays:
> _Custom Post Type Name_ Archive
Is it possible to add a custom page title for just that page? | You can use is_archive conditional code in your header.php to control the title
<?php if(is_archive()): ?>
<title>Archive page</title>
<?php else: ?>
<title><?php wp_title( '|', true, 'right' ); ?></title>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, page template, custom post type archives"
} |
Changing my site url from azure.net to custom domain
I have created a WordPress site using Azure so when the site went live the url was `
I changed this to ` using my domain hosting site and changing the settings on Azure.
However when I click on a post it changes back to `apidublin.azurewebsites.net` and stays like that. I know that in the general settings I shouldn't touch the wordpress url as I'm not looking to migrate the site but can I change the site url so I don't have this problem anymore? | Download and install "Velvet Blues Update URLs". Add your old url in the "Old URL" field, the new one in the "New URL" field, check all the checkboxes and click "Update URLs". Update your permalinks afterwards | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "urls, hosting, site url"
} |
WordPress Popular Posts Table Size Is Getting Big
I uninstalled WordPress Popular Posts plugin because it is getting slow lately. By digging to my database, I found that the table wp_popularpostsdatacache which is part of WordPress Popular Posts plugin is getting big. Currently it has 3,501,405 rows with 160.7 MiB used space.
I am thinking that this record was not cleaned because I am using nginx instead of apache. This happens to me on my Drupal site also. But I cannot confirm this. So, do you think this is because of nginx? If not, why it is getting bigger and bigger? It seems that the record there is not deleted.
I am using "Last 24 hours" option in Time Range option of this plugin. So I think a record of yesterday will be deleted automatically. But this is not the case.
Any idea about this? | This is really an issue with the plugin; I'd ask the plugin author for support.
If you are no longer using the plugin, use adminer or phpmyadmin to drop the `wp_popularpostsdatacache` table from the database. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins"
} |
Removing action from template class
I'd like to replace an action in a theme with my own version in a child. In this case, the theme hooks into `wp_head` to add it's own links. My own functions.php resides in the child theme and looks like this:
global $SMTheme;
remove_action('wp_head', array($SMTheme, 'headtext'));
add_action('wp_head', 'custom_headtext');
Unfortunately, it's not working yet and I'm fairly new to this. This is how the theme adds it's action:
class SMTheme {
var $options;
function SMTheme() {
// some unrelated code here
include TEMPLATEPATH."/inc/settings.php";
$reset='';
// if (current_user_can('administrator')) {}
$this->getparams($settings,$reset);
add_action('wp_head', array(&$this, 'headtext'));
} | include TEMPLATEPATH."/inc/settings.php";
is your problem.
> TEMPLATEPATH
is used by the parent theme
For child themes use
> STYLESHEETPATH
so your code will be
include STYLESHEETPATH."/inc/settings.php";
Alternatively you can use
get_stylesheet_directory_uri().'/inc/settings.php' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hooks, actions, child theme, wp head"
} |
Use of wp_insert_post and parameters
I've JUST started using WordPress..i'm trying to add posts to Wordpress using php and i came across this piece of code:
// Create post object
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
// Insert the post into the database
wp_insert_post( $my_post );
i understand this is the way to go when creating a post using php..my questions are:
1. how do we execute the above php script and where do we save it in the WordPress folder?
2. what does the 'post_category' array mean(i'd like to use a category id to add posts to WordPress)?
i'd like to mention that i've done some descent searching on the net but the resources i've found do not mention how to execute the above script. | Check the docs at < for the parameters to use with `wp_insert_post`
> This function inserts posts (and pages) in the database. It sanitizes variables, does some checks, fills in missing variables like date/time, etc. It takes an array as its argument and returns the post ID of the created post (or 0 if there is an error).
You run your function once in the context of a plugin, or worst case, in functions.php or in index.php and then remove it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, wp insert post"
} |
Set Transient expiration
I have a page that displays a random post every day. In order to change post every 24 hours I use
`set_transient('totd_trans_post_id', $totd[0]->ID, (60*60*24));`
What I'm wondering is this:
* Does the countdown (60*60*24) start as soon as I have inserted and saved the code?
* If yes: What happens if I let the code run for 23 hours, and then decide to "update" the code. Will the countdown restart?
* If no one visits the site for 48 hours, will the expiration still take place? Or does someone have to visit after 24 hours to "run" it? | 1. The countdown would start as soon as the transient is created or updated.
2. Running `set_transient()` on an existing transient value will restart the clock. Per the Codex page on `set_transient()`:
> If a transient exists, this function will update the transient's expiration time.
3. According to the Transients API page, the expiration time is the **maximum** lifetime of a transient value. _It may be deleted before the time is up_ , but it will never return its value after the time is up:
> Transients may expire before the $expiration (Due to External Object Caches, or database upgrades) but will never return their value past $expiration. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "transient"
} |
How to insert more than one row of data into a table at one time
I would like to populate a custom table, with more than one row of data at one time. If I delete the second array, it will insert one row of data. It won't add both rows at the same time though. How do I insert both rows at the same time? My code:
function mp_install_name_data() {
global $wpdb;
$table_name = $wpdb->prefix . "names";
$wpdb->insert(
$table_name,
array(
'id' => '1',
'name' => 'matt',
'age' => '20',
'point_one' => '0.45',
'point_two' => '0.22'
),
array(
'id' => '2',
'name' =>'james',
'age' => '6',
'point_one' => '0.27',
'point_two' => '0.17'
)
);
} | You could use a foreach loop -
function mp_install_name_data() {
global $wpdb;
$table_name = $wpdb->prefix . "names";
$rows = array(
array(
'id' => '1',
'name' => 'matt',
'age' => '20',
'point_one' => '0.45',
'point_two' => '0.22'
),
array(
'id' => '2',
'name' =>'james',
'age' => '6',
'point_one' => '0.27',
'point_two' => '0.17'
)
);
foreach( $rows as $row )
{
$wpdb->insert( $table_name, $row);
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "table"
} |
Retrieving a JSON feed of my posts and displaying thumbnails
I want to show a feed of my latest posts though json.
I seem to be able to do it - up to a point. I am retrieving my feed like so:
var json = <?php echo json_encode($query->get_posts()); ?>;
Problem is, I can't retrieve the post thumbnails, I can just retreive the post title and a bunch of other information, but can't seem to get what I'm looking for. Any idea how I can do that?
Thanks a lot! | Try something like this:
$posts = $query->get_posts();
foreach($posts as $p){
$thumb_id = get_post_thumbnail_id($p->ID);
$src = wp_get_attachment_image_src($thumb_id, 'image_size');
$url = $src ? $src[0] : false;
$p->image_url = $url;
}
$json = json_encode($posts);
Now you can echo out `$json` into your JS var. You will find the image url string in the key `image_url` of your json object. You can test if there is an image by testing if the value returned is false or not.
Be sure to change `image_size` in the `wp_get_attachment_image_src()` function to the name of the image size you want.
In essence we are looping over the query, grabbing the post thumbnail and finding the url of the image we want, then we add it to the object as a new property.
Any questions, just ask. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "json"
} |
How to get site homepage from plugin?
I am creating a plugin that has a preview, kind of like the theme customizer preview. It displays the users site in an Iframe. The issue is that I can't seem to be able to get the users homepage using the standard way of grabbing them, such as:
<iframe id="preview_frame" src="<?php get_bloginfo('url'); ?>"></iframe>
Or:
<iframe id="preview_frame" src="<?php get_home_url(); ?>"></iframe>
Can anyone shed some light on the proper way of doing this? Is their a specific way to display the site as a preview? I am using a hook to disable the admin bar in the preview, so if there is an elegant way to create a preview without the admin bar, it would be very good to know. Thanks. | You are just not using the right function. Try using this:
`<iframe id="preview_frame" src="<?php echo home_url(); ?>"></iframe>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, plugin development, jquery, ajax"
} |
Template directory in plugin
I have a custom dashboard plugin with one of the sections containing useful links. One of them should directly point to the documentation that comes with a template. This documentation is in the theme directory. Now I've tried different ways to get the path using for example:
<?php get_theme_root_uri(); ?>/mytheme/documentation/index.html
or
<?php get_template_directory_uri() ?>/documentation/index.html
but it outputs a URL to the homepage (` instead of full path to this file. Any advice? | I suppose, you want it to be like that:
<?php echo get_stylesheet_directory_uri(); ?>/documentation/index.html | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, theme development"
} |
making the [...] clickable
I have created a child theme for twenty twelve.
In this child theme I have added a `content.php` file and have copied and pasted the entire parent `content.php` and pasted it in to the child theme version.
I have changed this line.
<?php if ( is_search() ) : // Only display Excerpts for Search ?>
with this one
<?php if ( is_search() || is_archive() || is_author() || is_tag() || is_home() ) : // Only display Excerpts ?>
This reduces the post on my home page and added `[..]` to the end of it which is what I wanted it to do.
What I want now is for the `[..]` to be click able. So that it goes to the full post. Just like it does when you click the title. | Add the following piece of code just below `<?php the_excerpt(); ?>` inside the loop as explained in the codex Excerpt
<a href="<?php echo get_permalink(); ?>"> Read More...</a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "excerpt"
} |
Handle lots of images within the media uploader / selector
I currently have a website containing more than 3K images (and counting...) within the media library.
When the user opens the Media Uploader to select or upload an image to a post the media selector freezes and/or crashes while fetching the excessive amount of thumbnails.
I'm obviously looking for a way to fix this but not sure what direction I should take. | This really has nothing to do with WordPress itself; WordPress is fully scalable with appropriate hardware.
"the media selector freezes." Do you mean the whole browser window? Or the popup media library window?
The issue is going to be 1) the host server not having enough memory or bandwidth or CPU to display the page and number of images, or 2) the end user browser freezing from lack of memory. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "media, media library"
} |
What is the action or filter for adding information under the Permalink in Edit Post/Page?
I would like to add some HTML under the "Permalink:" in the Edit Post/Page page.
Under here:
!Under Here
So what is the action or filter? | You can try the `edit_form_after_title` action:
add_action( 'edit_form_after_title', function(){
echo '<hr/><div>My custom HTML</div><hr/>';
});
to add your custom HTML after the permalink:
!custom HTML
It will inject the HTML between `div#titlediv` and `div#postdivrich`:
<div id="post-body-content">
<div id="titlediv">...<!-- /titlediv -->
<hr><div>My custom HTML</div><hr>
<div id="postdivrich" class="postarea edit-form-section">...</div>
...
</div>
Tip: when you have question like this, best thing to do is look at source code.
The file responsible to output post edit page in admin is `/wp-admin/edit-form-advanced.php`
The hook you are looking for is **`'edit_form_after_title'`** as you can see at line #476 of that file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, actions, post editor"
} |
HTML Redirect to WP pages
I have some predefined links that I need to redirect to real URLs within my WP install. I have NO CHOICE but to use these URLs provided to me, unfortunately. The format is:
<
WP is installed at the root of mysite.com. I need to take the pagename query var, which will not be a direct match to a page URL and redirect it (301) to a WP permalink. I have attempted a few things in .htaccess with rewrites but not having luck mostly due to the fact that there are also WP permalinks redirecting.
Anyone done this before or know the best approach?
UPDATE - Here is the working code that I used based on the accepted answer below:
RewriteCond %{REQUEST_URI} ^/redirect.html(.*)$
RewriteCond %{QUERY_STRING} ^(.*?)&?p=page&?(.*?)$
RewriteRule (.*) /page/?%1&%2 [L,R=301]
I also added these before the base WP rewrites. | You could add something like this in your htaccess:
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^redirect\.html$ /%1 [L,R=301]
EDIT: based on comments, you'll need some additional conditionals to sort different query strings.
RewriteCond %{REQUEST_URI} ^/redirect.html(.*)$
RewriteCond %{QUERY_STRING} ^p=test$
RewriteRule (.*) /new-test/ [L,R=301]
RewriteCond %{REQUEST_URI} ^/redirect.html(.*)$
RewriteCond %{QUERY_STRING} ^p=pagename$
RewriteRule (.*) /new-page/ [L,R=301]
I also highly recommend this site for testing htaccess: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "redirect, wp redirect"
} |
Want the visual style in wordpress
In my WordPress installation when I want to post something there are only html style to write.
I see in video tutorial that a WYSIWYG editor should appear on the screen so I can write easily as I write in word processor.
So seems the visual editor in missing from my post edit screen. How do I get that back? | `Dashboard>>Users>>Edit User:` is "Disable the visual editor when writing" ticked? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "visual editor, wysiwyg"
} |
Plugins in WP_Options but not Active
Just completed a WordPress host migration. I had to disable plugins by deleting them in the WP_Options table. I have just added the correct plugins back into the db. However, the plugins are not active on the page.
My question is, what do I need to do now to activate the plugins so that they are in working order on the page again?
Thanks in advance. | Yes you will need to activate the plugins on the plugins page.
A side note:
For future reference if you need to disable plugins during a migration. Don't migrate the plugins across and wordpress will automatically disable them. Then you would copy them to the plugins folder and active as usual. This would also keep all the settings set prior to the migration. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, database"
} |
How can I show many posts an author has per week?
I've searched around and have had no luck or success in finding a way to show how many posts an author has made in a certain period of time (e.g. - a week)
Any ideas on how one would approach this? I just want to display the total number of posts an author has made in a given time period. | Have a look on the date_query parameter that has been added to WP 3.7 WP_Query#Date_Parameters and the author parameter.
Combine the two parameters as you need them to query all posts an author created in a given time:
<?php
$args = array(
'posts_per_page' = -1, // get all posts
'author' => get_the_author_meta( 'ID' ), // from this author ID
'date_query' => array( // in the last week
array(
'year' => date('Y'),
'week' => date('W'),
),
'fields' => 'ids' // only return an array of post IDs
),
);
$results = new WP_Query( $args );
echo count( $results ); // display the number of results
echo $results->found_posts; // display the number of results
?>
**Edit:** I updated this answer based on input from @birgire to behave more performant. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, wp query, author, date, date time"
} |
Add more widget areas to a theme
what's the best approach to add more widget areas to a theme? currently, my theme has 2 columns that display the widgets, but I'd like to extend it to 4 for example.
It currently looks like this: !enter image description here
And I'd like it to look like this: !enter image description here
All the widgets of this theme are located above the footer. The theme is called Time by s5themes.com. The widget initializer is not located in the functions.php as far as I know. Is this a simple fix at all? thanks!
Edit: Now that the sidebar is displaying in the theme, I think the rest of how each sidebar is shown is located in the style.css. Thanks. | You have to add this code in the `functions.php` file:
/**
* Register new sidebar
*
*/
function new_sidebar_widget_init() {
register_sidebar( array(
'name' => 'new-sidebar',
'id' => 'new-sidebar',
'before_widget' => '<div id="new-sidebar">',
'after_widget' => '</div>',
'before_title' => '',
'after_title' => '',
) );
}
add_action( 'widgets_init', 'new_sidebar_widget_init' );
and then call the sidebar from a template to display it:
<?php dynamic_sidebar( 'new-sidebar' ); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, widgets"
} |
Loading a sidebar on an Ajax call
I wanted to load a custom sidebar when doing an Ajax call, so I found the way with:
add_filter( 'loop_start', 'my_sidebar_widget', 25 );
but it is showing the sidebar even in media admin panel, so I thought about doing:
if( !is_admin() ) {
add_filter( 'loop_start', 'my_sidebar_widget', 25 );
}
but it was still loaded in the media admin panel, so I tried:
add_filter( 'loop_start', 'my_sidebar_widget', 25 );
if( is_admin() ) {
remove_filter( 'loop_start', 'my_sidebar_widget', 25 );
}
but in this way, the sidebar is not loaded on the Ajax call. Any idea of how to solve it? | `is_admin()` returns `true` if you're doing an Ajax request. So this is why my code didn't work. Instead I've done this:
add_filter( 'loop_start', 'my_sidebar_widget', 25 );
function my_sidebar_widget() {
if ( is_active_sidebar( 'my_sidebar' ) && (defined( 'DOING_AJAX' ) && DOING_AJAX ) || !is_admin() ) {
echo '<div id="my_sidebar">';
dynamic_sidebar('my_sidebar');
echo '</div>';
}
}
`defined( 'DOING_AJAX' ) && DOING_AJAX` returns true if you're doing an Ajax call, and `!is_admin` will work if you're not doing an Ajax request. In this way, it is not shown in the Media Admin Panel. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, ajax, sidebar"
} |
Remove tags from the kses filter
I know one can modify the kses filter to add new allowed tags to it, but is there a way to remove some of them? I can't find how. I need to disallow DIV tags.
Any ideas?
Thanks | The allowed tags are stored in `$allowedposttags` (located in `/wp-includes/kses.php`) as an array. For each element it looks something like this:
$allowedposttags = array(
'div' => array(
'align' => true,
'dir' => true,
'lang' => true,
'xml:lang' => true,
)
);
You can remove a single element of an array via `unset`
unset($allowedposttags['div']); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters, tags, html, wp kses"
} |
How to setup a permalink structure for a custom post type
I would like to know the correct way to setup the permalink structure for a custom post type.
Is there any attribute I am to set when I run a register_post_type() ?
e.g.
custom post type: product
expected permalink structure: /product/<slug> | I think you need to use the _rewrite_ argument.
Here's an example setting the url to _tips_
$args = array(
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'tips' ), // Here!
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 20,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields')
);
register_post_type( 'tips', $args );
More info: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, permalinks"
} |
exclude post from displaying in loop if it is in a category, but not in many categories
I am searching how to exclude posts from displaying in a loop if them are in a category x, but not in many categories... The Problem: if I do exclude posts i.e. out of category 5, all posts are listed in category 5 will be excluded. Also those which are also in category 3 and 1.
how do i exclude:
while (have_posts()) : the_post();
if(in_category($myCatsToExcludeArray)) continue;
...
... some general outputs
endwhile; | All you'll need to do is count() the get_the_category() results to determine how many categories your post is in, and check it along with your in_category().
For example:
while ( have_posts() ) : the_post();
if( in_category( $myCatsToExcludeArray ) && count( get_the_category( $post->ID ) ) == 1 ) {
do something
}
endwhile; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "categories, exclude"
} |
Customize the Dashboard Menu Editor
Go to `Appearance > Menu` in the ACP.
From there, you can select various items to include in your site's main navigation menu.
In the left column, you will see `Pages`, `Links` and `Categories`.
Since I'm using "Custom Post Types", I also see each Custom Post Type listed in between `Pages` and `Links`, which gives me the option of adding an individual post from each CPT into the website's Navigation Menu.
I'll never need to add an individual post from my CPT's into the navigation menu, so I'd like to remove my Custom Post Type boxes from the `Appearance > Menu` screen.
Google is taking me in circles because my question is about configuring the menu that configures the menu. | I found the answer after I typed out the question so I'll post it at the same time.
The solution is to set the `show_in_nav_menus` option to `false` when registering the Custom Post Type.
<
> **`show_in_nav_menus`** (boolean) (optional) Whether post_type is available for selection in navigation menus.
> Default: _value of public argument_ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, menus, dashboard"
} |
Add current class to queried term on taxonomy term archive
I'm currently using get_terms to list terms of a certain taxonomy. I would like to add a class to the term currently being queried via the archive template.
I tried putting together the below code but this bizarrely results in the class being applied to not just the current term being queried but every term AFTER it as well. I've tried comparing the slugs, ids and names of $term and $currentterm - all of which output correctly.
$terms = get_terms('MYTAX');
$currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
foreach ($terms as $term) {
if($currentterm->slug == $term->slug) $class = "live";
echo '<li class="'. $class .'"><a href=" $term->slug .'">' . $term->name . '</a></li>';
} | Try this instead:
$terms = get_terms('MYTAX');
$currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
foreach ($terms as $term) {
$class = $currentterm->slug == $term->slug ? 'live' : '' ;
echo '<li class="'. $class .'"><a href=" $term->slug .'">' . $term->name . '</a></li>';
}
Basically you just need to reset your `$class` variable back to an empty string after your conditional has returned false, otherwise it will continue to remain true. Its seems odd, but once you know how to handle it, its all good. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "taxonomy, terms"
} |
Renaming wordpress login and get new password button
I am currently building custom wordpress admin login theme.Now I have an idea but not sure it is possible.I want to rename "Get New Password" to something "Get New". Is it also possible to rename "Log In " to "Go"? | This is a bad idea for general usage plugin, unless you intend to supply translations for all the languages for which there is a wordpress translation.
If you need a new login form then use new strings for the text, don't override the string used in the wordpress login form, it give you no advantage to do that. This way the lack of translation will be expected not come as a surprise. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks"
} |
Wordpress Home Page
I'm setting up Wordpress version 3.8.1 on my website. It's installed at the domain root (` installation]`). I added a "Home" page. Afterward when editing the menu settings I noticed that there were two entries for Home. Upon further investigation I discovered that the Home page I made had a permalink of ` So, now I have two questions:
1. How do I fix the permalink for my Home page, so that it is `
2. Since I'm only able to get at one of the Home pages shown in the menu settings, how do I get rid of the extra Home page, so that I have only one editable Home page? | First, go to `WP-Admin > Settings > Reading > Front page displays > A static page (select below) > Front Page` and select your `Home`.
Second, go to `Appearance > Menus`, remove the duplicated `Home` entry and ensure the link of the other is pointed to ` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "homepage"
} |
wordpress is converting ?page=2 into /2
with this code
paginate_links(
array(
'base' => @add_query_arg('page', '%#%'),
'format' => '?page=%#%&a='.$a,
)
)
looks output like this
<a class="page-numbers" href="/wordpress/something/?page=2;a=1">2</a>
But when I click on it my url goes to `www.example.com/something/2/?a=1` is it possible to change it into `www.example.com/something/?page=2&a=1`?
Thanks | Try this. You can disable redirection by category name or page name or whatever you choose.
function wpren_disable_redirect( $query ) {
if( 'uncategorized' == $query->query_vars['category_name'] )
remove_filter( 'template_redirect', 'redirect_canonical' );
}
add_action( 'parse_query', 'wpren_disable_redirect' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pagination"
} |
Set the active Navigation Menu from a plugin
Is there a way to set the following option from a WordPress plugin, if you know the name of the menu you want to set: !enter image description here
My developer says it's not possible, but I am sure on of you gurus knows a way around this ;) | You can use the `wp_nav_menu_args` filter ( Codex reference ) to set a theme location to use a specific menu.
**Example:**
function test_wp_nav_menu_args( $args = '' ) {
// only set menu for the primary navigation menu.
if ( $args['theme_location'] != 'primary' ) {
return $args;
}
// change {main-menu} to be the slug of the menu you want to set.
$args['menu'] = 'main-menu';
return $args;
}
add_filter( 'wp_nav_menu_args', 'test_wp_nav_menu_args' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, menus, navigation, options"
} |
populate post meta in gravity forms
I can populate post author email with this code:
add_filter('gform_field_value_author_email', 'populate_post_author_email');
function populate_post_author_email($value){
global $post;
$author_email = get_the_author_meta('email', $post->post_author);
return $author_email;
}
It's ok, but how i can populate meta of post? meta = imail
I'm trying with
add_filter('gform_field_value_meta_imail', 'populate_post_meta_imail');
function populate_post_meta_imail($value){
global $post;
$meta_imail = get_post_meta('imail', $post->post_id);
return $meta_imail;
} | You have the arguments for `get_post_meta` backwards. You have:
get_post_meta('imail', $post->post_id);
Whereas, where you to check the Codex, it should be:
get_post_meta( $post_id, $key, $single );
Or is your case:
get_post_meta($post->post_id,'imail');
That is assuming that `$post` is set correctly and that you are using the Gravity Forms hooks correctly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post meta, plugin gravity forms"
} |
PHP Memory Limit vs. WP Memory Limit
I'm using TPC! Memory Usage Settings to monitor my installation's memory usage.
The plugin displays 'WP Memory Limit' which I know is set by the `wp-config.php`. It also displays 'PHP Memory Limit' which I'm guessing is set by the server host in the `php.ini`
This may be a dumb question, but is the 'PHP Memory Limit' the amount of memory I could possibly dedicate to 'WP Memory Limit'?
For instance, if I have a 'PHP memory limit' of `1000MB`, can I (should I) set my wp memory limit to `1000MB`?
Sidenote: The site is for a big website with lots of different operations, so many (necessary) plugins are installed and many users (up to 10) can be on making edits at any time. | `wp-config.php` sets the memory limit for the specific WordPress site which has that file. `php.ini` will effect your whole server. The `php.ini` is the parent setting, and so you can set WP to whatever you want within `php.ini`'s range.
It's also importan to note there is a `WP_MAX_MEMORY_LIMIT` where you can define a max amount of memory WP should use, especially if you have plugins gobbling up all the memory. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "memory"
} |
Change URL of plugin admin menu
Gravity Forms adds a Admin Menu called Entries that points to page=gf_entries. I am trying to modify this URL so that it defaults to page=gf_entries&id=2 instead. Below is the order of my WordPress Admin Menu. How can I update the URL of the Entries menu item?
Dashboard
Posts
Media
Forms
-Forms
-New Form
-Entries | Solution -
add_action( 'admin_menu', 'wpse_admin_menu', 100 );
function wpse_admin_menu()
{
global $menu, $submenu;
$parent = 'gf_edit_forms';
if( !isset($submenu[$parent]) )
return;
foreach( $submenu[$parent] as $k => $d ){
if( $d['2'] == 'gf_entries' )
{
$submenu[$parent][$k]['2'] = 'admin.php?page=gf_entries&id=2';
break;
}
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "admin menu"
} |
Registering different Post Formats for Blog Post and CPT
I'm using following code to register post formats for my blog posts ...
add_theme_support( 'post-formats', array( 'gallery', 'video', 'audio' ) );
Now, i want to add post formats support for my CPT 'Portfolio' too, but using different set of post formats. Using this code will add post format support for my CPT ...
add_post_type_support( 'portfolio', 'post-formats' );
But i only want to register _gallery_ and _video_ post format for portfolio CPT. Using the code below does'nt work ...
add_post_type_support( 'portfolio', 'post-formats', array( 'gallery', 'video' ) );
What code should i use? | I found an alternative approach.
There is a unique class in body tag for each post type. e.g for _portfolio_ post type i can use the CSS code something like mentioned below to hide the extra option.
.post-type-portfolio #post-format-audio, /* for radio button itself */
.post-type-portfolio .post-format-audio /* for option label */
{
display: none;
}
Hope it helps anybody else. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, post formats, add theme support, post type support"
} |
How To Get Parent Category Slug of Current Post
My theme has styling by category using the following code, which inserts the current category's slug as a CSS class.
<div class="CategorySpecificStyle
<?php $category = get_the_category(); echo $category[0]->slug; ?>">
<?php echo $category[0]->cat_name; ?>
</div>
Now i'm about to add a large number of new sub-categories, and it seems silly to add them all in CSS when I should be able to just select the parent category of the current post and apply styles to that.
I've been able to get the parent category's name:
$parentcat = get_cat_name($category[0]->category_parent);
But spaces (and capitalization) is an issue... And I can't seem to get the parent category's slug.
I know i'm probably missing a simple step somewhere, but any insight would be greatly appreciated. | You will need to use the ID value returned by `$category[0]->category_parent` and pass it through `get_term()`. Example:
$category = get_the_category();
$category_parent_id = $category[0]->category_parent;
if ( $category_parent_id != 0 ) {
$category_parent = get_term( $category_parent_id, 'category' );
$css_slug = $category_parent->slug;
} else {
$css_slug = $category[0]->slug;
} | stackexchange-wordpress | {
"answer_score": 26,
"question_score": 16,
"tags": "categories"
} |
Widget only in first post
I want to put a widget area into the content of the first post. My problem though is that is can't figure out how to get only the first post in my function. Here is my function:
function pietergoosen_insert_content_filter( $content ) {
ob_start();
$sidebar = dynamic_sidebar('sidebar-19');
$new_content = ob_get_clean();
if ( ! is_admin() ) {
return pietergoosen_insert_content( $new_content, 2, $content );
}
return $content;
}
If i replace
if ( ! is_admin() ) {
with
if ( ! is_admin() || is_paged() || $wp_query->current_post > 0 ) {
it shows the widget in all other posts and not in the first post. Any suggestions on a conditional tag for this | Assuming you are trying to add content only to the first post in the loop, a static variable should do it:
function pietergoosen_insert_content_filter( $content ) {
static $first;
$first = (!isset($first)) ? true : false;
if (true == $first) {
ob_start();
$sidebar = dynamic_sidebar('sidebar-19');
$new_content = ob_get_clean();
if ( ! is_admin() ) {
return pietergoosen_insert_content( $new_content, 2, $content );
}
}
return $content;
}
add_filter('the_content','pietergoosen_insert_content_filter'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, widgets"
} |
Plugin: Unable to Save the Image Alignment Option to Display in the Widget in the Sidebar
I am trying to add a select option to help user align the gravatar image. The problem is all value are saved except for the Image Alignment. When they select Image Alignment, it will revert back to "None"
<
Any help would be highly appreciated | On the update() function, you need to modify
$instance['image_alignment'] = isset($new_instance['image_alignment'] );
to
$instance['image_alignment'] = $new_instance['image_alignment'];
`isset()` is making the variable boolean, while you are expecting string. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, widgets"
} |
Printing errors during save custom post type
I am trying to debug my save_post function and cannot get the $_POST array to print so that I can see what's being posted. Please help!
add_action ('save_post', 'save_events');
function save_events($post_id){
if (('event' == $_POST['post_type']) && ('publish' == $_POST['post_status']) && ( $_POST['original_post_status'] != 'publish' )){
print_r($_POST);
//function code...
}
} | Either add a `die` after that `print_r()` or (better) use `error_log()` instead of `print_r()` and look at your php error logs for the output.
What's happening is WordPress is reloading content before you get a chance to see the output (in most cases). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
How to change the position of Jetpack sharing icons?
!Jetpack Sharing buttons settins
Typically Jetpack sharing buttons target the single page's `the_content()` function and echo the sharing icons just below the content. But for my site, I actually want it to **Disable** for `the_content()`, but to use it in some other `<div>`. I know I can check the "Disable CSS and JS" checkbox to disable the built-in functionality, but I actually don't want to code more and I like the default CSS of Jetpack sharing icons.
I simply want a Javascript code to alter the target of Jetpack so that instead of showing under the `the_content()` I can show it under another custom `<div>` of my choice.
Is it possible with any filter or hook?
P.S.: I just renamed the "Posts" to "Products" for my project. It's nothing to worry about. :) | remove_filter( 'the_content', 'sharing_display', 19 );
remove_filter( 'the_excerpt', 'sharing_display', 19 );
add_filter( 'the_content', 'share_buttons_above_post', 19 );
add_filter( 'the_excerpt', 'share_buttons_above_post', 19 );
function share_buttons_above_post( $content = '' ) {
if ( function_exists( 'sharing_display' ) ) {
return sharing_display() . $content;
}
else {
return $content;
}
}
Change the hook.
Related info < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "the content, plugin jetpack"
} |
Can I use Woocommerce to take orders but not handle payment?
I would like to create an ecommerce website.
In this website the customer will browse the product catalog, add the desired products to his cart, maybe create an account, and during the checkout phase, will leave a phone number along with his shipping information and address.
I will then manually review every order made (and be notified via email for new orders), call the person and handle it from then on.
Is this possible or do I have to let woocommerce handle the payments using a gateway like PayPal?
If it is possible, can someone please guide me how to set it up like so? | You can use multiple payment gateways. Simply use one of the default payment gateways that doesn't require immediately payment and you can rename it in the settings, so you have the same process that you described above. For example the "Cash on Delivery" gateway is ideal, you can edit the title and the description of the method in woocommerce settings. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 7,
"tags": "e commerce, woocommerce offtopic"
} |
Why cant I change the text on this theme?
I am a noob at website creation, and I have only recently begun to use wordpress. I looked at a bunch of demos online and they have helped, but I a seemingly simple problem.
My problem is that I am using the (free) theme from here and I cannot for the life of me figure out how to change the text inside that blue image. I want to remove "A bold big slider" and the sentence underneath it. But how do I do that?? Its becoming frustrating.
Thanks for any help. | Looking through the docs reveals that you can either disable that slider all together, or add your own slides in it which will replace the default text that you see now.
To add your own slides, use the instructions here: <
To disable the slider you should probably hunt for the option. I'm guessing that it's under Appearance > Theme Settings: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, text"
} |
how to change the verification url of pie register plugin of wordpress?
how can I change the verification url of pie register plugin? when any user registers it send a verifiaction url like this " " now how can i replace that wp-login.php with my custom login page and that "pie_verification" part also.I checked other registration plugins also but those doesn't even send an email to users. Someone please help. | Well I figured it out myself. I just did a simple trick. I reset the plugin and deleted it. And downloaded a copy of it in the computer, extracted it. Opened the pie-register.php and piewpnun.php on notepad++ renamed all the "pie_veification" and wp-login" with find button. Then I again installed it and before activating it just replaced those files in pie-register plugin folder with my edited files. Which did my purpose. Thank God. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php, url rewriting, email verification"
} |
Wordpress theme Modifications not showing up on live server
I have been working on localhost with a theme that was already installed on live server. After i completed my mods, uploaded the files to themes folder in wp-content but to my disappointment, the same old non-customized theme was showing up. Then I thought if I add my custom css codes to css editor then it will work fine but even after that nothing was showing up and I ended up with a totally messed up site. I tried to empty all the caches but still no luck. Before installing my custom theme, I actually deleted all the files associated with the old theme and then re-installed my own custom theme. For the sake of information, I am using Genesis Framework and I modified Genesis Sandbox HTML5 child theme. It works like a magic on my localhost but I don't know how to get it working.
Please help me. Any help will be appreciated. Thanks for reading. | You need to update your database. Before updating your database to the live server, you need to verify the URL. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "theme development, customization, child theme, cache, localhost"
} |
How to add the author search in the default wordpress search?
I would like to include the author search in the default WordPress search. Is there any way of doing this? right know it retrieves all the posts with the permalinks and author names. same way i need the authors search. is it possible? | This plugin called "WP Extended Search" looks like it would do the trick.: <
There's also this answer that may work for you: Possible to search by author name with default WordPress search function? | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 7,
"tags": "search, author"
} |
How to change the thumbnail size to a specific category?
I am using thumbnail on my blog posts. I added the following code in my **functions.php** for that purpose
add_theme_support('post-thumbnails');
set_post_thumbnail_size( 328, 228, true );
It's working fine and all thumbnails are **328 x 228**
Now I want to change the thumbnail size only for a specific category **ID is 9.**
Post under category ID 9's thumbnails must be **100 x 150.**
how can I do that? | How about just use conditionals:
if ( in_category( '9' )) {
// different size for one category
set_post_thumbnail_size( 100, 150, true );
} elseif ( in_category( array( '5', '7' ) )) {
// different size for multiple categories
set_post_thumbnail_size( 150, 200, true );
} else {
// default size
set_post_thumbnail_size( 328, 228, true );
}
**Reference:**
* Conditional tags
* in_category | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, thumbnails"
} |
Get data from custom post type to another custom post type?
I'am wondering if i can do this:
I have a Custom post type with named Staff, there you can create/add your staff.
Then I have another Custom post type called Projects.
When I add a new project i want a list of every Staff, and then choose a staff member that was active in that project.
So how do i get the data from Custom post type Staff to Custom post type Projects? | I would highly recommend the Advanced Custom Fields plugin. I use it pretty much on every project.
You can easily create the Post Object or Relationship connection. It's a great plugin with detailed documentation.
Posts 2 Posts is good as well, but last time I used it I needed to add code for connecting Custom Post Types. There wasn't straightforward interface to connect custom post types.
I hope that helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, customization"
} |
wpdb select from using array as search parameters
Similar to how you can insert into an array using code such as
$wpdb->insert( $table_name, $inputs); //where inputs is an array
I want to do a sql select statement with code such as
$wpdb->get_results("SELECT * FROM " . $table_name . " WHERE " . $input);
where input could contain several search parameters. Is anything like this possible? | Pass your information through `prepare` as in this example from the Codex:
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare(
"
INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )
",
array(
10,
$metakey,
$metavalue
)
) );
Your array should have the same number of elements as your query string has placeholders. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, array, select"
} |
When Author add new post change default status to pending
Same as above when Author add new post change default status to pending instead of published | Just set all users (authors) to _contributors_. Then they can only write posts and manage their posts but not publish them.
**Reference:** Roles and Capabilities
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, functions"
} |
How to link that "logged in" in "you must be logged in to post a comment" with custom login page on WordPress?
How to link that "logged in" in "you must be logged in to post a comment" for a post on WordPress to custom login page. So that when the user clicks on that "logged in" gets redirected to the custom login page not to the wp-login.php. Please help. | You could change the whole text by adding first parameter to your `comment_form` function. According to the Codex, the code below might help:
$comments_args = array(
// change the must log in text and link url
'must_log_in'=> '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), YOUR_CUSTOM_LOGIN_PAGE_URL ) . '</p>'
);
comment_form($comments_args);
Please change the 'YOUR_CUSTOM_LOGIN_PAGE_URL' accordingly. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "plugins, redirect, wp login form"
} |
How to individually set WP_DEBUG on a sub-directory multisite?
According to this question, it's possible to turn on/off `WP_DEBUG` for specific sites on a multisite.
Is it possible to do this with a **sub-directory multisite**? | You can do this by adding some code to wp-config.php
$request_uri = $_SERVER['REQUEST_URI'];
$debug_dirs = array ('/debug-dir1/','/debug-dir2/'); // list of directories to turn on debugging
foreach ($debug_dirs as $debug_dir) {
if (!strncmp($request_uri,$debug_dir,strlen($debug_dir))) {
define('WP_DEBUG', true);
}
}
define('WP_DEBUG', false); // debug off by default | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "multisite, directory, wp config, wp debug"
} |
Menu not always using correct link
I moved a Wordpress install from /wordpress/ folder to root by just copying the index and .htaccess file to root and then updating the permalinks etc.
All works fine but I have a problem with the menu in the top nav.
The menu works fine while you're on the main page and scrolls down to the area it should be. But when you go to one of the posts under services like < and then press on for instance "team" in the menu it will point to < thus suddenly adding the /wordpress/ to it and ending up at a blank page.
Anyone have an idea how I can solve this? | It appears that all of the links inside that menu are custom menu links, based on the classes "menu-item-type-custom" & "menu-item-object-custom".
You should be able to go into the menu and put whatever you want in the url field.
If you are using hash links (#team) and may have to put the full url ` as opposed to `#services`
You can also double check the Settings > General > Blog/Site URL to ensure that the /wordpress sub directory is not listed there.
Though it doesn't seem that those will actually link anywhere because there is no div with that ID on the page. Where are these links supposed to go to? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, navigation"
} |
Adding an Options Page to a Plugin
The first set of code adds a menu item to the sidebar. I'm attempting to add an options page (the type which shows up as a sub-page) under this. I tried to do so with the second code... but this isn't working.
How do I add an options page under a plugin's menu?
// Add menu page in sidebar
function admin_menu_wlseo() {
add_menu_page('SEO', 'SEO', 'manage_options', 'wlseo', 'options_page_wlseo');
}
// Add options page in sidebar
function admin_stuff_wlseo() {
add_options_page('Stuff', 'Stuff', 'manage_options', 'wlseo-stuff', 'options_page_wlseo');
} | @AndrettiMilas, If you really need a top level menu item (which is not encouraged), you should use `add_submenu_page`instead of `add_options_page`. Please refer to the Codex for the required parameters.
You could add the submenu like:
`add_submenu_page( 'wlseo', 'Submenu 1', 'Submenu 1', 'manage_options', 'wlseo-submenu-1')`; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php"
} |
Form Action submit over https
I am trying to make my website PCI compliant. It has a login form on top of each page in which the form tag is written like so:
<form id="wp_login_form" action="<?php echo site_url('wp-login.php', 'https') ?>" method="post">
According to wordpress documentation this should print an https url in the action, but it doesn't. Any idea why or how I should go about this? | As written, I'd expect to see ` as a response . I think you are missing a slash. `echo site_url('/wp-login.php', 'https')` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, wp login form"
} |
Object [object Object] has no method 'slides'
I am using the enqueue function to link two javascript files. I get this error `Object [object Object] has no method 'slides'` I checked and I am not loading jquery more than once. The code that is causing this error is
jQuery(document).ready(function ($) {
$('#slides').slides({
preload: true,
preloadImage: '<?php echo get_template_directory_uri(); ?>/images/loading.gif',
play: 5000,
pause: 2500,
hoverPause: true
});
});
Example Link | Try use `slidesjs` instead of `slides` in your code. Update your JS from:
`$('#slides').slides({`
to
`$('#slides').slidesjs({`
if you're using SlidesJS. BTW, I found an error that you shouldn't use PHP tag in your JS code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, wp enqueue script"
} |
When does a function assigned to the content_filtered_edit_pre filter hook fire?
I added a function to the filter hook tag `'content_filtered_edit_pre'`, but it doesn't seem to fire no matter what I do. I am also aware of `'content_edit_pre'`, but I am curious as to when this filter hook is called. The following does not result in 'filtered ' being added to the front of my post when I open it in the edit screen, even after another filter has been run:
function test_of_content_filtered_edit_pre( $content, $post_id ) {
return "filtered ".$content;
}
add_filter( 'content_filtered_edit_pre', 'test_of_content_filtered_edit_pre', 10, 2 );
The only documentation I can find on the Internet seems to be from the wordpress codex or copies of it. | This is activated within the `sanitize_post_field()` function:
> Calls 'edit_{$field}' and '{$field_no_prefix}_edit_pre' passing $value and $post_id if $context is 'edit' and field name prefix is 'post_'.
So in the case of the `post_content_filtered` field, the filters are
edit_post_content_filtered
and
content_filtered_edit_pre | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, hooks"
} |
What's the difference with trash_comment and wp_trash_comment?
I don't understand when I'm suppose to use trash_comment over wp_trash_comment.
What's the difference? | Where did you see `trash_comment`? It is no original WordPress core **function** , though. Maybe some part of a plugin/theme?
So in short: use `wp_trash_comment` \- if you must.
There is, however, an **action** called `trash_comment`. Maybe this is what got you confused...? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, trash"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.