INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How can draft post after 1 year
I need to do this in my post in custom post type, I need when to day publish new post. After 1 year from today convert post status from publish to draft.
How can do that ? | Try this code (maybe working) , but i'am not sure cause not testing :
function amin_show_expire(){
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type = 'CUSTOM' AND post_status = 'publish'");
if( !empty($result)) foreach ($result as $a){
$show_time = get_the_time("Y-m-d", $a->ID );
$show_time=date("Y-m-d", strtotime("+1 years", strtotime($show_time)));
if ( $show_time < date("Y-m-d")){//compare 1 year after post with current time
$my_post = array();
$my_post['ID'] = $a->ID;
$my_post['post_status'] = 'draft';
wp_update_post( $my_post );
}
} // end foreach
}
add_action( 'init', 'amin_show_expire' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts"
} |
Custom Javascript not working?
Basically I want the effect to look as it does here
But mine won't do the effect I currently have a button but it won't activate the effect for the menu to pop open.
site that I'm using to test it on here
Any help would be appreciated.
I think the script classie.js which changes div's classes isn't working but I can't figure out why | There are a few problems but the main one is when sidebarEffects.js is loaded the HTML it's looking for doesn't exist yet. So...
var container = document.getElementById( 'st-container' )
// and
buttons = Array.prototype.slice.call( document.querySelectorAll( '#st-trigger-effects > button' ) )
are both empty when the script is run.
Easiest way to fix it is to put your `<script>` tags right before the close of your `<body>` tags instead of in the `<head>`. If you're including these files into your theme manually, no problem, just stick them in your theme's equivalent to `footer.php`. If you're enqueueing them, see the $in_footer param here: <
You also have two containers with the `id="st-trigger-effects"`. See here: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, javascript"
} |
Reduce font size
I need your assistance regarding my problem. In fact, I've tried to change the slider's font size on my website : < on the style.css file, but the changes are not taken in account. Any help ?
| Not a WordPress question, but add the following in your stylesheet:
.featured-text h2, .featured-text h2 a {
font-size: 24px !important; /* set font size */
}
In the future, simply _Inspect Element_ to find which class or tag to style. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css"
} |
Is_template how to add one more template
I have wordpress theme which is adding some scripts and css trought functions php. I want to add one more template file , but don't know how. Any ideas? This is what I have. Will be happy for any answer . THANKS!
// add styles per template
if ( ztheme_is_template('base-gallery-rail.php') {
wp_enqueue_style('ztheme-gallery-style'); | Here's an example using the default WordPress `is_page_template` function:
<?php
if ( is_page_template( 'base-gallery-rail.php' ) ) {
wp_enqueue_style('ztheme-gallery-style');
} else if ( is_page_template( 'other-template.php' ) ) {
wp_enqueue_style('other-style');
} else { // the last else is only required if you want to have a default
wp_enqueue_style('default');
}
You can add as many `else if ( blah ){ //do stuff }` as you need. If you get above four or five, consider using a `switch` statement. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php"
} |
Woocommerce get category image full size
i'm trying to get the full size image of my category products.
$prod_categories = get_terms( 'product_cat', array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true
));
foreach( $prod_categories as $prod_cat ) :
$cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
$cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );
$term_link = get_term_link( $prod_cat, 'product_cat' );?>
<a href="<?php echo $term_link; ?>"><img src="<?php echo $cat_thumb_url; ?>" alt="<?php echo $prod_cat->name; ?>" /></a>
<?php endforeach; wp_reset_query();
The above code works, but it returns an image of 150px x 150 even when adjustments in Woocommerce are like this:
 for the solution using: `wp_get_attachment_image_src`
$prod_categories = get_terms( 'product_cat', array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true
));
foreach( $prod_categories as $prod_cat ) :
$cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
$shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'shop_catalog' );
$term_link = get_term_link( $prod_cat, 'product_cat' );?>
<a href="<?php echo $term_link; ?>"><img src="<?php echo $shop_catalog_img[0]; ?>" alt="<?php echo $prod_cat->name; ?>" /></a>
<?php endforeach; wp_reset_query(); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "categories, woocommerce offtopic, images, terms"
} |
Metabox not being added
what is wrong with my code ? why it doesnt add meta box ?
add_action('admin_menu', 'clivern_plugin_top_menu');
function clivern_plugin_top_menu() {
add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug', 'clivern_plugin_top');
}
function clivern_plugin_top() {
add_meta_box('custom-page', 'Custom Page', 'show_custom_page_metabox');
do_meta_boxes('my-top-level-slug', 'normal', 'saed');
}
function show_custom_page_metabox() {
echo "asd";
} | That code doesn't call the metaboxes of the good screen.
Try this to call the metaboxes of the current screen.
do_meta_boxes('', 'normal', 'saed'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "metabox"
} |
Blog post date not in format required by schema.org
I'm trying to display blog posts using the BlogPosting schema from Schema.org, but I am having difficulty getting the date to display in the required format.
Currently, the responsive_child_post_meta_data() function contains the following:
<time itemprop="datePublished">%2$s</time>
But when I try to validate the results using the W3 HTML Validator, I get the following error message:
Error: The text content of element time was not in the required format: The literal did not satisfy the time-datetime format. Syntax of time-datetime: One of the following: month, date, yearless date, time, local date and time, time-zone offset, global date and time, week, non-negative integer, or duration. For more information and examples, see the section on the datetime value in the HTML specification. | Not sure what `responsive_child_post_meta_data()` is but I use this and it validates just fine:
<time itemprop="datePublished" class="published" datetime="<?php echo get_the_time('c'); ?>" content="<?php echo get_the_time('c'); ?>">
<?php echo get_the_date(); ?>
</time> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "html5"
} |
Counter of posts ever posted - even deleted ones
I'm trying to figure out how can I display the amount of posts ever posted - not only the currently published, draft + pending etc ones, but even the deleted ones.
I assume that there has to be created some kind of a counter that every time a post is published gets increased by one.
Any ideas?
P.S. I'm talking about a custom post type | Depending on your needs, WP Query may not work for this since it won't include posts that have been deleted after the trash has been emptied. This should work (but hasn't been tested):
function wpse_custom_post_type_counter() {
$number = get_option( 'wpse_custom_counter' ) ? absint( get_option( 'wpse_custom_counter' ) ): 0;
$number++;
update_option( 'wpse_custom_counter', $number );
}
add_action( 'publish_your_custom_post_type', 'wpse_custom_post_type_counter' );
You'll need to update the function and option names to suit your application. Also the slug for your custom post type should replace `your_custom_post_type` in the call to `add_action`.
One disadvantage of this approach is that it will only work going forward, it won't be able to count existing posts.
Hope that helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, count"
} |
Reduce Drop down Menu Width in Wordpress
i have used drop down menu. its have two brands of column one watch another knife. previous watch have 5 column drop down mega menu. i had removed two column. its now showing extra black space. how to remove it ? i have used menu-full-width when i create menu . this is my site Link
> Site LINk
please help me ? how to reduce extra black space drop down? watch brands ? any idea about ? | It's a css issue. You need to edit two selectors.
First is the menu width. It's set to 100% which is why you're seeing black space. Edit this class below.:
.cap-primary-menu .menu > li.menu-full-width .cap-submenu-ddown {
padding: 20px 25px 25px;
width: 100%; // set this to auto or something smaller than 100%
left: 0;
border: 1px solid #eee;
background: #fff;
}
The li tags within that menu are set to be divisible by five, minus some padding, which is why you see 18%. So you need to change this selector:
.cap-primary-menu .menu > li.menu-full-width .cap-submenu-ddown .container > ul > li {
width: 18.297%; // change this to 30% and go from there.
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, themes, woocommerce offtopic"
} |
API calls on plugin activation or init?
When I activate my plugin, I need to call an API, to get some items, lets say fruits, flowers and animals. I need to create taxonomy terms out of these items. Then I need to loop over these items and make API calls to get some children items per item, like fruits - Apple, Banana, Guava etc., flowers - Rose, Lily, Jasmine etc. I need to create children terms out of these children items. Later some more API calls will be added to the code, to get data for each child item and create custom posts from them. Currently I am doing it on plugin activation. But it looks like the plugin activation is slowing down due to so much processing. Is there a better place or hook to do these activities? Can I use `init` to perform some API calls which can be suspended for a later time? | on the plugin activation hook, instead of doing everything right there just set a cron job that will do it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, performance, activation, init"
} |
Get the the title of Wordpress after comma
I've read that you can get the title before comma(,) Get the title before comma
but wondering how can I get the title **after** comma(,) ?
is it also possible to use strtok()? or are there similar function?
Thanks. | You can use in this way
<?php
$sTitle = "Your, Title";// From get_the_title(); or other sources
if(strpos($sTitle , ",")){
$sTitle = substr($sTitle , strpos($sTitle , ",") + 1);
}
echo $sTitle; // You can also trim($sTitle); to remove whitespaces left from substr()
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php"
} |
user added by(who added this user)
I want to know who added every user in all users menu in the back-end, I used 'get_the_author' but it must be within the 'loop' which cann't be in all users menu that the condnition willnot be verified, Could anyone help? | I use a plugin called WP Security Audit for tracking all things any additional users on sites im building are doing on the backend. You can set the plugin to only show to certain user roles as well. Link: < If you're only trying to see this information on the backend that may help | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users"
} |
Add drop down to widget if it is in a certain area
Is there a way to programmatically add a dropdown selector to any widget added to a given widget area?
I have a header widget area and I'd like any widget added to it to have a dropdown box with the option to align the widget to the left right or centre. This would then be used to print a css class which would align the widget... | Widget CSS Classes is probably your best friend. It has the ability to add CSS classes manually by just typing them in, or you can set up predefined items that will add classes automatically. It's quite handy. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets"
} |
Is there a way to get minimal Wordpress functions for iframed content?
I have a bit of content in a PHP file that is designed to live inside an iframe on another page. The PHP file is very simple-- here it is in its entirety right now:
<div class="content-tos">
<?php
// get the terms of service from other page
$getpage = get_page_by_path('/terms-of-service');
echo apply_filters('the_content', $getpage->post_content);
?>
</div>
Obviously I need to include something above these lines of code so the PHP has access to the Wordpress core functions (like `get_page_by_path()`)... but if I use `get_header()` I get my entire header, nav bar, Google Analytics tracking code etc, which then appear inside the iframe, which I definitely don't want.
Is there a way in Wordpress to do some kind of include that will give me the basic Wordpress API but won't draw a full HTML header, etc, etc, etc from the `header.php` file? | If you don't want `get_header`, then don't call `get_header()`. It's a simple as that, the `get_header` function is not where all of the WP core is initialized. The simplest way to do this is using the template hierarchy to create a template for a specific page slug or id.
From the WP Admin, create a page at the URL you want to use.
Then create a template file that follows the rules for overriding the template for that specific page.
wp-content/themes/<your-theme>/page-tos.php
From there you can put whatever you want in `page-tos.php` and have full access to WP functions and API. And you can disable it by simply unpublishing the page from the WP Admin as well. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "headers"
} |
How to remove Customize from admin menu bar after WP 4.3
WordPress 4.3 brought more updates to the customizer. It also added a new option at the top admin menu bar that says 'Cusomize' and has a paintbrush. How can I disable this menu from showing up? We don't use the customizer, and I would not like our users clicking on it either.
We currently do `$wp_admin_bar->remove_menu('comments');` but I do not know the term for the customizer. I tried both customize and customizer (guessing) but neither seemed to work. | `customize` should work. I was able to remove the Customize link with the following code:
add_action( 'wp_before_admin_bar_render', 'wpse200296_before_admin_bar_render' );
function wpse200296_before_admin_bar_render()
{
global $wp_admin_bar;
$wp_admin_bar->remove_menu('customize');
} | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 5,
"tags": "functions, admin menu, theme customizer"
} |
Posting to admin-ajax from front end. Is this redirect ok?
I'm posting a form to `admin-ajax` and the redirect use to be within the success handler. That was taking too long to receive from the server then redirect, even though it was only a small json response giving a success message. I've since moved the redirect to execute after the `.ajax()` call. Is there any chance the redirect could execute before the AJAX posted? I know AJAX is asynchronous so it's executing in the background.
jQuery.ajax({
type:"POST",
url:admin_ajaxurl,
dataType: "Json",
data: {
action: "lp_contact",
post: postData
},
beforeSend: function(jqXHR, data, setting){
},
success: function(data){
},
error: function(data) {
}
}); // End update prospect
window.location.replace("
return false; | The problem could be in using admin ajax. If you switch to a different endpoint, the process may speed up.
I've used ajax flow on a few sites and you should see a performance gain: <
Check out some best practices here:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "ajax"
} |
Licensing a Plugin
I am developing some paid for premium features for my plugin which is already available in the WP Repo.
What are the best ways to validate licensing etc. for premium features? I want to continue to use the repo so "calling home" is not an option as it is against plugin guidelines.
These features are to be purchased annually so there is an expiry to consider. I'm fine with the coding side of things, just looking for a best practice method to provide a license of type without users being able to manipulate the expiry date - I accept the date will be within the DB somewhere and I am fine with that - I trust the users not to manually change
thoughts appreciated
Thanks | The only 100% way to get a paid subscription kind of service working is to move part of the functionality to an external server which is under your control and manage payment, expiry, etc there.
When the code is not under your control you can not limit its use, this is a very basic life fact of software development, especially when the source code can be easily modified. "Calling home" by itself doesn't really help much if I can edit the code and remove the check without hurting the functionality.
Since you can not prevent "bad users" from manipulating your code it is better to avoid thinking too much about protection. If your plugin will provide actual service in a good price point then most people will be willing to pay for it instead of wasting time on pirating it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, licensing"
} |
Display posts with date wordpress default
I'm trying to display last posts with WordPress date, not date from server.
<?php
$week = date( 'W' );
$year = date( 'Y' );
$query = new WP_Query( 'year=' . $year . '&w=' . $week );
while ( $query->have_posts() ) { $query->the_post();
// Page title
the_title();
} // end while
// Restore original Post Data
wp_reset_postdata();
// Save memory
unset( $query );
;?>
what is wrong? How i can use to show last x day posts with date wordpress default? | you need to study about date query. Anyways following should work
<?php
$args = array(
'posts_per_page' => -1,
'date_query' => array(
array(
'after' => '7 days ago'
)
)
);
$query = new WP_Query($args);
while ( $query->have_posts() ) { $query->the_post();
// Page title
the_title();
} // end while
// Restore original Post Data
wp_reset_postdata();
// Save memory
unset( $query );
;
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp query"
} |
Password protecting template, secured content not showing if even password is right
Here is mine below code. Now thing is that It perfectly asks the password for secured page.
But if even I add correct password. I still page asking for password.
Below is mine code.
<?php
/**
* Template Name: Page
*
*/
global $post;
if ( ! post_password_required( $post ) ) {
get_header();
?>
<div id="Content">
<div class="content_wrapper clearfix">
secured content here
</div>
</div>
<?php
get_footer();
}else{
// we will show password form here
echo get_the_password_form();
} | I solved issue with suggestion of @TheDeadMedic.
Below is the code. As he told added while have post. I added it after header.
<?php
/**
* Template Name: Page
*
*/
global $post;
if ( ! post_password_required( $post ) ) {
get_header();
while ( have_posts() ) { the_post(); }
?>
<div id="Content">
<div class="content_wrapper clearfix">
secured content here
</div>
</div>
<?php
get_footer();
}else{
// we will show password form here
echo get_the_password_form();
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "password"
} |
Trouble implementing python on WordPress
I followed all the directions in this post and I still cannot get a result to display. I know PHP is doing _something_ , because there is no text displayed whatsoever. The result has a header and no body content. When the plugin is disabled, it displays the shortcode as plain text.
<?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */
add_shortcode( 'python', 'embed_python' );
function embed_python( $attributes )
{
$data = shortcode_atts(
array(
'file' => 'hello.py'
),
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'], 'r');
$read = fread($handle, 2096);
pclose($handle);
return $read;
}
I uploaded **hello.py** and **Python.php** to the plugins folder and made sure the plugin was properly activated.
In my post editor I have: [python file="hello.py"]. | Ok, I found the solution. First of all, you have to
> $handle = popen('env python '. **DIR** . '/' . $data['file'], 'r');
More importantly, I had to install Python 2.7.2 on Bluehost | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, shortcode, python"
} |
How do I use WP's jQuery
I am trying to learn WP theme development. And I just learned that WP already has a jQuery version included. Until now I have been using the jQuery from Google's CDN.
So I just now deleted the CDN link from my code. And of course all my jQuery code stopped working.
So I guess I am missing something. What do I need to do if I want to use WordPress's local jQuery?
When I search SE QA and Google all I can find is how to un-register the local jQuery version and then register CDN. But that is not what I want to do. I want to use the local jQuery.
So what am I missing? | WP's jQuery is not mapped to `$` like you may expect, it is loaded in `noConflict` mode so you'll need to use `jQuery()` instead of `$()`, unless you map it yourself.
When you include your js file you'll want to make sure to set jQuery as a dependency as well:
wp_enqueue_script( 'your-script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ), '1.0.0' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "jquery"
} |
Use WordPress user database in external php application
As the title tells I'm looking for a solution on how to use my wordpress database in an external php application. I want to use Wordpress because I want only one place for users. One place one password.
I tried including the wordpress blog header but it only works on my blog domain, and not on my domain where I have my php application.
On wordpress.com they have there single sign on thing, I want something like it. I found this and it looks like they use curl and an api looking really simular to WP-REST Api for the sso thing.
Can I use WP-REST api or 0auth with my blog to integrate?
Any help, example, how to's, tips,guidance are very welcome! | If your main concern is using your Wordpress database for user authentication, I'd look into the WP OAuth Server plugin.
We use this for authentication with a 3rd party mobile app: app users type their username and password into the app which then - thanks to the plugin - authenticates them against their credentials in our Wordpress database. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "api, curl"
} |
I am unable to publish/update post
I am running wordpress 4.3 with my custom theme. Everything was going fine but today when i tried to post new article on my blog i notice that when i click on publish button it stuck on loading. I tried so many times but faced same problem. Please see attached screenshot. . Then i clicked on quick edit and change the status draft to publish and then it publish successfully. Please see attached screenshot.  and just add this to the bottom of the file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, css"
} |
How do I turn these values from MYSQL into an array
I am working on a custom query to show a few posts. I am able to output all the post ID's. I am trying to turn these ID's into an array so I can use 'post__in' => $myarray in my query. How can I do this?
<?php
$allposts = $wpdb->get_results("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5");
foreach ($allposts as $singlepost) {
echo '<p>' .$singlepost->music_id. '</p>';
}
?> | Use $wpdb->get_col. It will return a one-dimensional array that you can use in `post__in`
$allposts = $wpdb->get_col("SELECT `music_id` FROM `custom_table` ORDER BY id DESC LIMIT 5"); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, array, php"
} |
Stop theme displaying comments
So with all comments disabled on pages/posts theme's still display any existing comments.
Is there a way to programmatically stop this happening without adjust the theme's code?
My plugin uses comments as a journalling type system to log all changes to (custom) posts. On the front end, when my client is logged in there are a number of pages the plugin provides and I do not want the comments to be displayed, but even with comments turned off, existing comments (journal entries) are shown at the foot of the page, which I do not want | OK I think I figured this out...
add_action( 'init', array( &$this, 'no_comments' ) );
function no_comments() {
add_filter( 'get_comments_number', '__return_false' );
}
Removes the comment count and the comments themselves | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, comments"
} |
What hook/filter can I use to add/edit/show/hide the title under (on hover) links on the table view?
I'm not entirely sure the name given to these links, but the class is called "row-actions".

{
$actions['custom_link'] = '<a href=" Custom Link</a>';
return $actions;
}
add_filter('post_row_actions', 'add_custom_link', 10, 2); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "filters, hooks"
} |
Is there a filter to remove or replace the post title's link in the admin post table view (edit.php)?
I thought I could use the filter `the_title`. But that let's you change the text only. I would like to disable the title link for specific pages. So the title text would stay the same, but the user wouldn't be able to click on it and get to the edit post page. I can think of two ways of doing this.
1. Adding a class to disable the link via css.
2. Disabling or removing the link vis JS.
Before going either route, I wanted to know if there's a filter that will accomplish that without having to resort to JS or css?
I have been searching the codex and hookr.io for filters , but I cannot find anything. | I would try something like below. Since `current_user_can` is called right before displaying the link, we have to hook where capabilities are checked.
function wpse200630_has_cap_check( $allcaps, $caps, $args, $user ){
if( function_exists( 'get_current_screen' ) ){
$screen = get_current_screen();
if( $screen->base == 'edit' && $screen->post_type == 'my_post_type'){
if ( 'edit_post' == $args[0] || 'delete_post' == $args[0] ) {
if( !empty( $args[2] ) && $args[2] == ID_TO_DISABLE )
return array();
}
}
}
return $allcaps ;
}
add_filter( 'user_has_cap', 'wpse200630_has_cap_check', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin"
} |
How to add and submit input fields using a shortcode?
How can I add and submit the post without user login? By that I mean an offline user can add some content on WordPress and submit it, like simple forms in PHP.
I tried this code:
public function add_shortcode_fileds() {
add_shortcode( 'add_fields', 'input_fields' );
function input_fields( $atts ) {
$atts='<form method="post" action="">';
$atts.='<input type="text">';
$atts.='<input type="submit">';
$atts.='</form';
return $atts;
}
} | You can create the shortcode like this:
add_shortcode( 'add_fields', 'input_fields' );
function input_fields( $atts ) {
if ( isset( $_POST['gg'] ) ) {
$post = array(
'post_content' => $_POST['content'],
'post_title' => $_POST['title']
);
$id = wp_insert_post( $post, $wp_error );
}
?>
<form method = "post">
<input type="text" name="title">
<input type="text" name="content">
<input type="submit" name="gg">
</form>
<?php
}
It's just a sample usage, you can check in detail here. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "shortcode, forms"
} |
Jetpack Mobile Theme: when on smartphone on categories the theme suddenly changes to jetpack mobile theme even though it's deactivated
I'm having a little problem with my mobile theme. I'm using a Momentous Lite child theme for my website. On my Smartphone the home page looks as it's supposed to do but as soon as I switch to a category, the theme changes into jetpack's mobile theme even though I deactivated that... Does anyone know why?
My website: <
example of a category: <
Thanks! | This is because you most likely need to clear your cache. If you have any plugins like WP Super Cache or WP Fastest Cache installed then navigate to there settings and click clear all cache. Also if you have CloudFlare (or something similar) running on your website then you can purge the cache on that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, themes, mobile, plugin jetpack"
} |
count_many_users_posts except current logged in user?
Is there a way to count and show the count of all author posts in a custom post type except the current logged in user?
I was hoping there's a way to do it with `count_many_users_posts` but it doesn't appear there is a way to exclude authors, only include them.
I've done multiple searches but have found nothing to even hint at a right direction to head in.
Here's the codex example:
<?php
$users = array(1, 3, 9, 10);
$counts = count_many_users_posts($users);
echo 'Posts made by user 3: ' . $counts[3];
?>
TIA!
ON EDIT:
Just wanted to let y'all know I haven't revisited this yet. I will try the solutions and come back when I get there. Another project popped up for the moment.
Thanks! | I don't know why this works, but it does.
$authorid = get_current_user_id();
query_posts(array(
'post_type' => 'tasks',
'author' => -$authorid,
) );
$count = 0;
while (have_posts()) : the_post();
$count++;
endwhile;
echo '<p class="else"><em>' .$count .'</em></p><span class="description">All other posts</span>';
wp_reset_query(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, posts, count"
} |
How to modify get_the_excerpt() when post-format equals 'quote'?
How can I modify the `get_the_excerpt()` when the `post-format` of the post is set to `quote`? | While writing the question in SE I already found the solution:
add_filter( 'get_the_excerpt', 'get_custom_the_excerpt' );
function get_custom_the_excerpt($excerpt) {
$post = get_post();
$format = get_post_format( $post );
// modify excerpt if it is a quote, for example set title as author
if ($format == 'quote') {
$output = '<q>'. $excerpt. '</q>
<p class="quoted">'.get_the_title().'</p>';
}
// return excerpt without change
else {
$output = $excerpt;
}
return $output;
}
For details check get_the_excerpt() and get_post_format(). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, post formats"
} |
Multisite login and redirect to users main blog,
On the multisite main page (< I have a login-form where users can login to their multisite like so:
<?php
$args = array(
'redirect' => get_active_blog_for_user(),
);
wp_login_form( $args );
?>
After logging in they will be redirected to their dashboard (http:// example.com/userblog/wp-admin/). I don't want them to be redirected to their dashboard. I want them to be redirected to their mainpage instead (< How can I achieve this?
Kind regards Johan | I solved this and I only use:
wp_login_form();
Since I don't want users to get access to the wp-admin area at all I use the following code:
// Restrict users from accessing the admin-area
function restrict_admin()
{
if ( ! current_user_can( 'manage_sites' ) ) {
wp_redirect( site_url() );
}
}
add_action( 'admin_init', 'restrict_admin', 1 );
// Disable admin-bar for users
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('manage_sites') && !is_admin()) {
show_admin_bar(false);
}
}
Kind regards Johan | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, redirect, wp login form"
} |
How to load API's in WordPress?
I am trying to learn WP Theme development. And I am wondering what's the proper way to load api's? For example Google Maps:
`<script src="
Should I enqueue the API url, or how should I do? I am a bit confused since this api for example reffers to a /js folder and not a direct script? | For google maps in a template file, I just do this:
wp_register_script( 'google-maps-api', ' );
wp_print_scripts( 'google-maps-api' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp enqueue script, api"
} |
Using Grunt and keeping theme comments
I used Grunt to minify CSS then combine them together in my WordPress theme. I combined all the CSS into 1 file called main.css . However in order to register the theme I still need a style.css with theme comments. The issue is Grunt gets rid of comments. I would like to do achieve this in 1 http request vs 2. I would like to have all my css in style.css right below the theme comments and get rid of main.css. How can I accomplish this? | `style.css` may contain only comment with Theme Name: ... . It just tells to WordPress about your theme. You have no need to load style.css in theme through tag `<link ... >`.
So. Now you can leave your only one css file `main.css` with all styles in `<head>`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, css"
} |
Set add_image_size() greater than content width in media box
How can I set a image size bigger then the defined max content width in the media box?
The content width is set to:
if ( ! isset( $content_width ) ) {
$content_width = 960;
}
If I add now a picture with size bigger then the `$content_with`, it get scaled down.
add_image_size( 'post-visual', 2048, 900, true );
The picture gets sized but at the moment it appears in the media box only with the dimensions of `960x421`. | 1. Did you use `wp_get_attachment_image_src('$post_id','post-visual');` for getting your desire image sized? If not then try to use this function for getting proper image size.
2. Check CSS for that image `width` or `max-width` and it has to be `width: 100%;` css property. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "images, content width"
} |
How to use Bootstrap with WP's jQuery?
I am using WP's local jQuery. All my own scripts are working fine! But bootstrap gives me this error message in the console: `Uncaught Error: Bootstrap's JavaScript requires jQuery`.
How can I make bootstrap using WP's local jQuery? | Ideally, using WP methods to enqueue bootstrap JS dependencies you can just set jQuery as a requirement and WordPress will take care of the rest.
<?php wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/bootstrap/js/bootstrap.js', array( 'jquery' ) ); ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "jquery, twitter bootstrap"
} |
special characters not supporting in wordpress
First I dont know from which thing I am facing problem. I have created a wordpress website and it was working fine. I have moved it later to justhost.com and then I have got this problem. Special characters are not supporting. This is a wordpress website. I dont know coding that much. Please help me. 
It seems that the content is in base64 form and it needs to be decoded.. Hope it helps :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, database, htmlspecialchars decode"
} |
Child Theme not loading parent CSS
I'm using the MyStile theme for a new site. I'm trying to create a child theme so I can modify the theme and not have my changes overwritten, however once I activate my child theme, the whole styling seems to go from the website all together.
I'm guessing the issue here lies somewhere when it's calling the parent _style.css_ file.
Here's what I have in my child theme's _style.css_.
/*
Theme Name: Blurred Edge Apparel
Theme URI:
Description: MyStile Child Theme
Author: Blurred Edge Apparel
Author URI:
Template: mystile
Version: 1.0.0
*/
@import url("../mystile/style.css");
I have also copied across _header.php_ and _footer.php_ from the parents theme directory, however still no joy.
Am I missing something here? | Take a look at How to create a Child Theme and you'll see that:
> the previous method to enqueue the parent stylesheet was to import the parent theme stylesheet using @import: this is no longer best practice. The correct method of enqueuing the parent theme stylesheet is to add a wp_enqueue_scripts action and use wp_enqueue_style() in your child theme's functions.php.
Here's the example provided:
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "theme development, themes, child theme"
} |
custom template only for content
I've been trying to get into wordpress plugin development but I still haven't figured out how to customize just one part of the template, I've seen the single-{post-type}.php method, but this changes the whole template altogether.
Another method I've seen is short codes, but they become the content as in they are put inside the content container that I'd want to change itself but I want to change the parent.
I guess the most simple way I can exaplain this is that I want to change content.php of a theme for certain post types from a plugin
So let's say that I'm creating a plugin that is going to display a list of items that it's going to get from the database and I need to change only the way it's displayed inside content, what would I do? | You can't override template parts. Even if you could, you would have no way of knowing what template part you'd need to replace. A theme is only required to have an `index.php` file and there are no restrictions or naming convention for template parts.
Your options are to create a full template and leave it up to users to better integrate it with their theme (like Woocommerce does, for example), or add a filter to `the_content()` to customize the markup just within the output of `the_content()` function.
**EDIT** \- you can override full templates from a plugin via the template filters. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, templates, content"
} |
How to add a zero before numbers in WordPress Post Pagination?
I want my POST pagination to show the numbers from 1 to 9 like this: 01 02 03 04 05 06 07 08 09 10 11... and NOT like > 1, 2, 3, 4...
Actualy i have this code:
<?php wp_link_pages( array( 'before' => '
<div class="page-links clr">', 'after' => '</div>
', 'link_before' => '<span>', 'link_after' => '</span>' ) );?> | `wp_link_pages()` does not have a parameter for what you want. So I'm thinking you can make use of the filter hook `wp_link_pages_link`, which has two - `$link` and `$i` \- parameters, where `$i` is the page number. You can use WordPress' `zeroise()` function to get the format you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pagination, codex"
} |
.htaccess file changes disappear
This is what happens in a Wordpress (Woocommerce) site I've been asked to investigate.
1) I make a modification to .htaccess and save it.
Here's output of the ls -command
% ls -l
ll
-r--r--r-- 1 user group 248 Sep 7 11:31 .htaccess
2) Just a moment later
% ls -l
-r--r--r-- 1 user group 235 Jul 20 09:42 .htaccess
The changes have disappeared. Note the changed date in the file (apparently it is copied from somewhere).
What is causing this? And how do I stop it from happening? | I was having a similar problem recently. It turned out it was due to a code injection in the /wp-includes/nav-menus.php file. There was a Base64 malware code injected that was causing my .htacess file to chmod itself to 444. Something called some kind of darkleech malware. See this link for more, maybe it's what's happening in your case as well: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess, server"
} |
How to create new page can get custom field other post in wordpress
I want to create a new page eg: example.com/demo/2222
in which: demo is a page, 2222 is id of a post.
This page can retrieve data from the custom field of post 2222
when i change 2222 to other id post, custom field also change same.
hope everyone can help me :) Thanks | That is possible, but it's to hard to do that, becouse you should make a rewrite rules for pages..
Easiest way is to make url something like: `example.com/demo?post_id=2222`
then you can get `post_id` like these: `$post_id = (int) $_REQUEST['post_id'];`
and pass it to some function to get custom field atc.. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
How to use title attributes in sidebar widget?
I have a custom post type "article" & I need to display some custom urls is a widget in the sidebar using `php code widget`. When I use this code withing the loop it works perfectly:
<a href="<?php echo site_url('/article/full-text/'); ?>
<?php $slug = $post->post_name; echo $slug; ?>" title="<?php the_title_attribute(); ?>">Full Text</a>
but when I put this code in the php code widget it displays only the first part of the url. To be more clear, when I use this code within the loop the url will be (`www.my-site.com/article/full-text/article-title`). But in the php code widget the url will be (`www.my-site.com/article/full-text/`). Am I missing something here? Any help please? | You'r missing $post variable ( it is not defined and that for you don't get post_name ).
As a solution you could add `global $post;`
You'r code would be like:
<a href="<?php echo site_url('/article/full-text/'); global $post;
$slug = $post->post_name; echo $slug; ?>" title="<?php the_title_attribute(); ?>">Full Text</a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, widgets, urls"
} |
How to trace SUBMIT button
I have a form that I created using a plugin which upon clicking the Submit button, it's redirecting to a URL that I selected in the form's settings. But the problem is that any other form that I create, it gets directed to the same URL that I selected on my original form. I need to trace the Submit action to see where its going and what functions are being called. Any thoughts and suggestions will greatly be appreciated. | Still using jQuery, you can do this:
$('form').submit(function() {
// Use this to echo in JS console.
console.log( $(this).attr('action') );
// Use this to display a popup.
alert( $(this).attr('action') );
});
This will track **every** form being submitted.
Place this between `<script>` tags or in a JS file. Like @dev said, this for debug purpose, don't keep this in your code.
You may have to wait for Document to be ready, then you'd use :
// Needs jQuery too.
$(function() {
// Copy code here.
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, actions"
} |
Get All IDs Of A Post Type Using WP_Query
I am trying to get a list of a custom post type's IDs using WP_Query, but it is returning undesired result, which is a memory leak and stuck browser.
Here is the code I use:
$the_query = new WP_Query("post_type=post&posts_per_page=-1&field=ids");
if ($the_query->have_posts()) {
while ($the_query->have_posts()){
echo get_the_ID();
}
}
It makes my browser infinitely trying to load the page. May be somebody know what's wrong with the code above.. | You are missing the `the_post()` function call in the loop. Just add
$the_query->the_post();
in your loop. Apart from that, your loop should work
## EDIT
You should also not forget to reset your postdata after the query is done | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "wp query, id, post type"
} |
update post category in a new table on frequent change of category
I am creating a new voting plugin
1. I have created a table name 'wp_vote_info', it has four fields'id', 'postid', 'type_of _vote', current_category.
2. When some user vote on that particular post,i am storing the postid, and type of vote(up or down), current_category given for that post.
**Problem to be solved:**
3. For a period of time the post category may be set as ('Software') after some days or hours it may be changed to (Technology). At that case 'current_category' field should be update based upon the 'postid'.
**Note:** (On update of post category it should also update in the New table 'wp_vote_info'). | You could use an Action Hook '`save_post`' to implement the requirement and this way categories will stay synced with your custom table and default tables.
Example :
function post_updated_sync_category( $post_id ) {
//Here you get postid of the post being updated
//You can put your code to update in custom table here
}
add_action( 'save_post', 'post_updated_sync_category' );
You can use this hook with custom post type as well, here is how you can implement this, see WordPress Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, updates"
} |
the_author_posts_link css class
Currently I'm styling as project where I need to add a custom CSS to `the_author_posts_link()`.
I want to add the class "blog-link" with the `the_author_posts_link()` . How do I add a css class to it? | You can use the `the_author_posts_link` filter to add the custom `blog-link` class:
/**
* Add the 'blog-link' class to the output of the_author_posts_link()
*/
add_filter( 'the_author_posts_link', function( $link )
{
return str_replace( 'rel="author"', 'rel="author" class="blog-link"', $link );
}); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "php, css, author"
} |
Append custom field items to content from plugin
I know you can use
add_filter( 'single_template', 'modify_page_template' );
function modify_page_template($single_template) {
global $post;
if ($post->post_type == 'post' || $post->post_type == 'page') {
$single_template = dirname( __FILE__ ) . '/post-type-page-or-post.php';
}
return $single_template;
}
to replace the default theme and add your custom field items, but is there any way to do it without modifying the WHOLE THEME, instead just append the meta box data into the content? | You can use the `the_content` filter to add code directly into the content.
add_filter( 'the_content', 'wpse_202010_modify_the_content' );
function wpse_202010_modify_the_content( $content ) {
global $post;
if ( in_array( $post->post_type, array( 'post', 'page' ) ) ) {
$content = '<p>New content here</p>' . $content;
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, metabox, page template"
} |
What Can I Use To Add A Custom Button Between Publish button and Move To Trash?
I want to insert a custom button between "Publish" button and "Move To Trash" link. What can I use to make this?
Here is a screenshot to make this clearer:
 {
print '<button>Hey!</button>';
});
Result:
;
I found these in `wp-admin/edit-form-advanced.php` and I can't figure out purpose of these actions ( checked for add_action( 'do_meta_boxes' ... ) there is no such actions ).
Documentation says
> Fires after meta boxes have been added.
>
> Fires once for each of the default meta box contexts: normal, advanced, and side.
But what's purpose is for these action? When should I use these actions?
**NOTE:** it's not the same as `do_meta_boxes()` function and has nothing common with it! | As explained here:
> [The] do_meta_boxes [action] is designed to let people manipulate the registered meta boxes once they are registered but before they are rendered.
So the `do_meta_boxes` hook is not for doing (that is: displaying) the meta boxes. This is because:
> When the do_meta_boxes actions was moved out of do_meta_boxes() it should have had its name changed. add_meta_boxes was added in 3.0 to be the hook that we should have renamed do_meta_boxes to be. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "actions"
} |
Replace string with post_name on sidebar
I'd like to replace all `{POST_NAME}` 's from my text-widgets on `single.php` sidebar. I'm thinking of something like this
global $post;
$POST_NAME= $post->post_name;
$sidebar = preg_replace('/\{(POST_NAME)\}/e', "$$1", $sidebar);
How can I get sidebar HTML into `\$sidebar` | Your code looks well and considerations are correct. In order to achieve your goal, I'd collect HTML and wrap it up like this:
Instead of calling `<?php dynamic_sidebar($sidebar_id); ?>` use `<?php dynamic_sidebar_replaced($sidebar_id); ?>` with a function (add it to functions.php) below:
function dynamic_sidebar_replaced($sidebar_id) {
if (is_single()) { // Optionally, to ensure you're at the single post template.
ob_start(); // Start gathering output
dynamic_sidebar($sidebar_id);
global $post;
$POST_NAME = $post->post_name;
$sidebar = preg_replace('/\{(POST_NAME)\}/e', "$$1", $sidebar);
ob_end_clean();
echo $sidebar;
return '';
}
dynamic_sidebar($sidebar_id);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp insert post"
} |
WP CLI theme install. Install a private repo?
I have a bash script that installs and activates a theme like this:
wp theme install < \--activate
The problem is that it only works with public repositories, rather than private ones. If I make the repository private I get this error:
Unpacking the package...
Warning: The package could not be installed. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature
Is there a way I can install private repositories that I have ssh keys and passwords for? | I actually figured out a way to do this. First you use wget like this:
wget --user username --ask-password -O path/to/output.zip
the -O flag specifies output and output.zip is where you want it to download to.
Then you can run:
wp theme install path/to/output.zip --activate
Happy days | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "scripts, wp cli"
} |
Wordpress plugin database. How to create table for checkbox
Hi i have following code that adds table to database when the plugin is activated. For the moment they are only for input fields. I need to create a table for checkbox or yes/no. Thnaks
$sql = "CREATE TABLE $easy_gallery_table (
Id INT NOT NULL AUTO_INCREMENT,
name VARCHAR( 30 ) NOT NULL,
slug VARCHAR( 30 ) NOT NULL,
description TEXT NOT NULL,
thumbnail LONGTEXT NOT NULL,
thumbwidth INT,
thumbheight INT,
PRIMARY KEY Id (Id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql ); | You can add above code on plugin activation hook so that code run whenever you activate plugin.
For checkbox You need to define table column type as Boolean.
Dont forget to check table is already exist or not. otherwise it show error on second activation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
How to restrict users and admin from creating new taxonomy terms?
I've created taxonomy (schedule_day_taxonomy) for a specific custom post type (schedule).
add_action( 'init', 'schedule_day_tax_func' );
function schedule_day_tax_func() {
register_taxonomy(
'schedule_day_taxonomy',
'schedule',
array(
'hierarchical' => true,
'label' => 'Day',
'query_var' => true,
)
);
}
Now the taxonomy `DAY` appears only in the custom post type `schedule` I've created `7 terms' from the admin panel.
 ) : ?>
needs to be satisfied to display the " _Add New Category_ " link.
You can set the _capabilities_ for your `schedule_day_taxonomy` taxonomy, when you register it.
## Example
Only users with the `edit_schedule_day_taxonomy` capability can edit the taxonomy:
add_action( 'init', 'schedule_day_tax_func' );
function schedule_day_tax_func() {
register_taxonomy(
'schedule_day_taxonomy',
'post',
array(
'hierarchical' => true,
'label' => 'Day',
'query_var' => true,
'capabilities' => array(
'edit_terms' => 'edit_schedule_day_taxonomy',
),
)
);
}
Without this capability, users can't edit this taxonomy. If you need to edit it, you can remove this from the code above or assign it to your _admin_ user. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, terms"
} |
Disordered sidebar in admin panel of self-hosted blog network
This is how my self-hosted blog network's sidebar started to look, starting from yesterday:
. It happens in every blog that belongs to my blog network, including blog network dashboard.
It started to happen yesterday, event though there was no update to my Wordpress, neither manual nor automatic. I have the newest publicly available, stable version of Wordpress behind my network (4.3).
This isn't very annoying, though makes my life a little bit more miserable! :> However, I'd like to know, if this is a know bug or issue, that happens on other computers or if this is limited to my computers only? | This is a recently discovered bug in Chrome 45 and should be solved in Chrome 47.
Steps to solve according to WP issue tracker:
* Open in Chrome chrome://flags/#disable-slimming-paint
* Enable the **Disable slimming paint flag**.
* Ensure that the **Enable slimming paint** flag below it is not turned on.
* Relaunch Chrome using the button below flags. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin menu"
} |
Additional folder where will Media Library look for files
I have additional folder (images/) in wp-content/uploads/ directory to store theme images (I heard it is good practice to place them in upload directory) and I want Media Library to list this files because I might need to reuse them somewhere else. Is there a way to tell Media Library to look for files in whole uploads directory (or manually add directories to look in) maybe using functions.php? | The Media library doesn't directly pull from the `uploads` folder. It reads in Attachments, which place their attached media in the `uploads` folder. If you want to access them through WordPress, you will need to upload them as Attachments. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, media library, directory"
} |
Display number of images actually posted
I'm currently using this PHP code to pull the number of images from a post.
$attachments = get_children(array('post_parent'=>$post_array[0]['ID']));
$image_count = count($attachments);
It is currently pulling any image that is "attached" to the post, however I would like for it to pull the actual number of images that were used in the post. How would I display the number of images actually displayed in the post? | Something like:
$image_count = substr_count( $post_array[0]['post_content'], '<img');
It won't cover images in galleries ... but you can count IDs in gallery shortcode. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images"
} |
What's the proper way to sanitize checkbox value sent to the database
I have tried using `sanitize_text_field()` and `esc_attr()` to filter checkbox data when saving their values to the database, but it is causing the data not being saved.
What is causing it and what's the correct way to filter input `checkbox` and `radio`? | I would use the filter_var() function. It has some predefined filters that you can use depending on what kind of data you are expecting such as string, number, etc.
So to sanitize for a number:
$sanitizedNum = filter_var($yourVar, FILTER_SANITIZE_NUMBER_INT);
For a string you would just change "_NUM_INT" to "_STRING".
Wrap those in a custom function then. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, security, save post, sanitization, radio"
} |
multi-language multi-site with REST API
I am creating a site with multiple sub-sites that should support multiple languages and be queryable with a REST API.
The site itself is mostly a CMS with various pages and maybe some posts for events. The sub-sites are cities in this case, each with a different administration. Multiple languages means that every page can (but does not have to) be translated in any language.
Being fairly new to Wordpress Development, I am not sure if and how the different components work together.
WPML seems to have multi-site support. Apparently, there is also a plugin connecting it with the popular WP-REST-API.
Can somone confirm the cross-functionality by any chance? I would like to be at least somewhat sure before purchasing WPML. | Yes, WPML works well with multi-site and also with the WP-REST-API (even without further plugins). | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "multisite, api, multi language, plugin json api, rest api"
} |
Scripts not loading when using the wp_enqueue_scripts action
Really basic, I'm afraid. My scripts aren't loading when I put them as part of a function triggered by the `wp_enqueue_scripts` action in `functions.php`. If I put them outside of that action as part of the main file, they load fine, but of course this is bad form. So:
wp_enqueue_style( 'intranet-style', get_stylesheet_uri() );
works but throws up errors in debugging but
function intranet_scripts() {
wp_enqueue_style( 'intranet-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'intranet_scripts' );
does nothing, it doesn't even throw up any errors. I must be missing something super basic but I can't for the life of me see what it is. Help? | `get_stylesheet_uri()` loads the **main stylesheet** of the theme. If you need to load additional stylesheets, you need to use `get_template_directory_uri()` for parent themes and `get_stylesheet_directory_uri()` for child themes.
If you have stylesheet called `custom.css` in the root in a child theme, you will use `get_stylesheet_directory_uri()' . /custom.css'`
You should also make sure that you have `wp_head()` inside your `<head></head>` tags in your header | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, actions, wp enqueue script, wp enqueue style, scripts"
} |
Remove empty rows from the database
I'm writing a script to alter the post content column in the database and I just notice it has a lot of empty rows, these seem to be deleted posts that now have no content or anything, I don't like them.
Could i just `DELETE from posts WHERE content = '';` without breaking anything?
The database has around 40k rows, i can't afford to break it, its backed up tho. | I'd imagine those rows with empty content are more often then not revisions rather than trashed posts. To make sure you don't delete stuff you want to keep I suggest you add the `post_status` to your SQL, using `trash` and `auto-draft` as value - the latter are the revisions. Btw the table column is called `post_content` not content. So your SQL would look something along the lines of the following:
DELETE FROM wp_posts
WHERE post_content = ""
AND post_status = "trash"
OR post_status = "auto-draft";
You could of course use `$wpdb` and its `delete` method to achieve the same. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, mysql, content"
} |
Add custom argument to WP_Query and modify SQL where clause
I'd like to be able to hook into WP_Query in such a way that I can add a custom argument to my WP_Query like:
$q = new WP_Query([
'my_cool_arg' => [ 1, 2, 3 ]
]);
and then access this and modify the where part of the generated SQL query. I am aware of the **posts_where** filter, but I don't know how to access the arguments from that filter. | Solved it. The filter **posts_where** takes the query object as a second parameter. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, sql"
} |
How to add a second stylesheet to the editor
Is it possible to add another stylesheet from my theme directory, to the `Appearance > Editor` screen?
.
Side note: always try to avoid relative urls in wordpress forms. It is too easy to end up with the form at a place where the relative url points to nothing. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, wp admin, forms"
} |
Admin: sub menu doesnt display under apperance when activate my themes
I got a strange issue in WordPress. I build a themes for WordPress. when I activate my theme, some sub-menu under appearance in admin panel where missing.
 {
add_theme_support( 'custom-background' );
} );
This would trigger the display of the "Background" menu item in the Appearance sidebar, but it would not affect your theme, you would need to hook into it and implement the theme features. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "theme development, menus, themes, admin menu, sub menu"
} |
No option to allow search engines to index my site in WP 4.3
I have launched a new company website, when I was setting up the wordpress install locally I believe I clicked 'do not allow search engines to index this site' despite only developing offline. Now I have taken it all online, and updated to 4.3 there is not option to allow indexing, anywhere in the settings page. There is only a radio button to 'discourage', but nothing to positively allow indexing.
Im pretty miffed about this, and now I'm worrying that the page won't be indexed and we will lose business, because the domain was used on a previous website that gets good traffic and is listed on google, but I'm thinking that the index will expire soon if wordpress is set to refuse google to index the pages?
Many Thanks in advance, | This feature was changed in Wordpress 3.5 already and was moved from _Privacy_ to _Settings -> Reading_. You where in all propability using a very old Wordpress version.
You now just have the option to discourage indexing by search engines
* Checkbox ticked -> Search engines should not index your site, however this will not force search engines not to index the site
* Checkbox unticked -> Search engines are allowed to index your site
So, in short, you don't have anything to worry about, your site will be indexed by default when the discourage checkbox is unticked | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "options, privacy"
} |
How to show 1-5 of X Total Results
I know I'm doing something that's been done 1000's of times before in WordPress, but struggling to get the terms to find it on the Interwebs.
I've got a custom category template page and have a while loop that shows the first 5 results (of which there are more than 5).
How do I output something within my while that shows the relative position in the results and the total number:
I know how to get the post count:
<?php
$catcount = new WP_Query( 'cat=4&posts_per_page=-1' );
?>
But not sure how to setup the pagination and the relative results, meaning
Results 1-10 of `<?php echo $total->found_posts; ?>`
How do I get the results values 1 of 2 and then create pagination for subsequent pages? | it's been a long time, I had exact the same task and here is the solution
$from = ($query->query_vars['posts_per_page'] * $paged) - ($query->query_vars['posts_per_page'] - 1);
if(($query->query_vars['posts_per_page'] * $paged) <= ($query->found_posts)){
$to = ($query->query_vars['posts_per_page'] * $paged);
}else{
$to = $query->found_posts;
}
if($from == $to){
$from_to = $from;
}else{
$from_to = $from.' - '.$to;
}
It's not the perfect code, but it works in most of situation. Have a nice day!) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, pagination"
} |
how to display featured image for single post for a specific category
I used this function to display featured images on top of single posts and it works great. But I need it to only apply to the category 'team' with an ID of 31.
I have tried every possible combination I can think of. When I use the conditional the featured image does not display no matter what.
Here is the code:
/* Code to Display Featured Image on top of the post */
add_action( 'genesis_before_entry', 'featured_post_image', 8 );
function featured_post_image() {
if ( ! is_singular( 'post' ) ) return;
if ( is_category( 31 ) ) {
the_post_thumbnail( 'post-image' );
}
} | `is_category` checks whether or not the current page is the Archive Page for the specified category, not if the current post is in the category. You want `in_category`.
/* Code to Display Featured Image on top of the post */
add_action( 'genesis_before_entry', 'featured_post_image', 8 );
function featured_post_image() {
if ( ! is_singular( 'post' ) ) return;
if ( in_category( 31 ) ) {
the_post_thumbnail( 'post-image' );
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, conditional tags"
} |
How can i display custom menu in sidebar?
I would like to display a custom menu in a custom sidebar instead of author information or blank space i.e custom menu with similar styles as default menu but only in vertical manner as displayed in grey in the below picture.
, 8 );
Thanks! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "oembed"
} |
How can you customize on a multisite?
How do multisites have the ability to customize the look of the theme (menu color, style, etc.) without changing it for everyone else.
Where are these separate files stored? | Looking into the Theme Customizer API, it appears that theme modifications are stored as `theme_mod`s which can be access using `get_theme_mod( $mod_name )` or (if you want to grab them all) `get_theme_mods()`.
Peeking into the source of `get_theme_mods()`, I see that the mods are stored in the site's `options` table as `theme_mod_$mod_name`. So the theme modifications are stored in the database, not in any files.
## References
* Customizer API
* `get_theme_mod()`
* `get_theme_mods()`
* Options API | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
Add a logout menu link
How can I add a logout link in my websites menu? Is there a PHP code or link that I can use to be able to do this?
Thanks | I don't think there is a link that you can use to do it but there is some PHP. I personally like the following tidbit of code to add it.
<?php
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
ob_start();
wp_loginout('index.php');
$loginoutlink = ob_get_contents();
ob_end_clean();
$items .= '<li>'. $loginoutlink .'</li>';
return $items;
}
?>
You can also use this PHP code which basically does the same thing.
add_filter('wp_nav_menu_items','show_register_login_link');
function show_register_login_link($nav) {
// The "Register" link is not offered if the Administration > Settings > General > Membership: Anyone can register box is not checked.
return $nav.wp_register("<li class='menu-item'>", "</li>", false)."<li class='menu-item'>".wp_loginout(get_site_url(), false)."</li>";
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "menus, login, logout"
} |
Is there a way to disable formatting shortcuts in 4.3?
Since the WordPress 4.3 version was released there are these new things called formatting shortcuts. They can be helpful but I find them mostly annoying. Is there anyway to disable these new formatting shortcuts?
Thanks in advance! | Yes, there is very well a way to disable these formatting shortcuts. You can do so by using this simple little piece of PHP code.
<?php
function disable_mce_wptextpattern( $opt ) {
if ( isset( $opt['plugins'] ) && $opt['plugins'] ) {
$opt['plugins'] = explode( ',', $opt['plugins'] );
$opt['plugins'] = array_diff( $opt['plugins'] , array( 'wptextpattern' ) );
$opt['plugins'] = implode( ',', $opt['plugins'] );
}
return $opt;
}
add_filter( 'tiny_mce_before_init', 'disable_mce_wptextpattern' );
?>
Hopefully that helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "visual editor, formatting"
} |
Why should I use the esc_url?
This thing makes my coding difficult. Wordpress codex reasons the use of esc_url by talking vaguely about security. But is it really worth the trouble?
For example, what's the important, practical security benefit by using
<?php echo esc_url( home_url( '/' ) ); ?>
instead of
<?php echo home_url() ?>
PS: I am not talking about theme development, but about a specific site. | If you check the documentation on Data Validation it has following to say about the function:
> Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols [...], eliminates invalid characters, and removes dangerous characters.
There you have it — practical security benefit. Valid protocol, no murky characters.
The answer about necessity is firmly **yes**. Escaping output is the most basic security practice. | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 17,
"tags": "security"
} |
Do changes to Wordpress permalink custom structure affect old urls?
Will changing WP permalink custom structure affect old posts URL?
For example. I have a large group of posts that follow this custom structure: /blog/%category%/%postname%/
I want to change it to /blog/
Or better yet, be able to manually add structure after the root domain for every post.
So that I have the option to manually enter /%category%/%postname%/
I'm hoping that changing my permalink custom structure will only affect new posts going forward and old posts remain unchanged. | Yes.
You may want to use a redirect plugin to setup redirect rules for your inactive urls. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, permalinks"
} |
Retrieve posts by page in wp rest api
I want to develop an app for my WordPress.org website. I am using wp rest api to receive post in json. My question is how do I retrieve posts page by page. For example if there are 50 posts I want to receive 1-10 then 11-20 and so on. | Well, you can add `?page={$page_number}` to the URL that you're requesting.
See, for example, <
It appears to split the posts into pages of 10.
## Reference
* WP-API documentation (I found this in the docs for v1 of the API, but per the sample URL above, it works on v2 as well) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rest api"
} |
How can I make post view count editable?
In the admin panel, under posts, I see all posts with their view counts next to them. How can I make the view count editable?
I am working on certain things that will kick in when a post reaches 100 views for example, and I want to set it manually for testing purposes.
Your help is much appreciated! | Just posting an answer so I can close this. It seems the post view counter I see is part of my theme, not a core feature of Wordpress as I thought. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "views"
} |
How to Pass values to Custom Field through PHP in WordPress Posts?
Suppose i have a function
function mytable(){
$count_value = get_kudos_count( $post_id ); }
How to send `$count_value` dynamically to the custom field present in WordPress post ?
Let us assume the custom field name (key) is `custom_count` | You can use `update_post_meta`:
update_post_meta( $post_id, 'custom_count', $count_value ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, advanced custom fields"
} |
Users credentials and syncing from third party with WooCommerce
I am trying to build a web store for a client who has already had a mobile app. the mobile app team would like to sync user's password as they update it both on the mobile app and the web store.
Also, they would like to authenticate users password either with user ID or email agains the webs store from the mobile app with some sort of API.
I am trying to figure out how to do these with WordPress REST API and WooCommerce REST API, or perhaps WordPress built-in auth.. but I am having a hard time wrapping my head around this.
What would be the best approach to this problem? Any help would be greatly appreciated as I am new to the API and authentication.
Cheers! | You can use wp-api. Its really easy and best. The documentation is also very clear and vast. Its provide a small plugin which can do everything you want. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, api, password, authentication"
} |
WP_Query posts_per_page ignored
I struggle already for a few hours with the `posts_per_page` ignored in my `WP_Query` :
[query] => Array
(
[post_type] => Array
(
)
[posts_per_page] => 4
[meta_key] => _touchsize_likes
[orderby] => meta_value_num
[order] => DESC
)
The result has `found_posts = 18` and `12` posts in the `posts` array.
Even if the only parameter set is `posts_per_page`, the results are wrong.
Checked the `query_vars['post_type']`, the value is 4. Tried with `suppress_filters => true`, still no effect.
Any idea ? | It were the sticky posts who ignored my `posts_per_page`. After setting `'ignore_sticky_posts' => true` the result was correct ! | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "posts, wp query, limit"
} |
Reveal hidden submenus on page load - Twenty Fifteen theme
How can I reveal hidden submenus on the page load in the Twenty Fifteen theme? I would like it so that all the submenus are open on every page. Can someone please guide me on how this can be achieved? Thanks | Figured it out! Use the following PHP code.
/*
* Toggles the menu dropdowns to open state
*/
function mod_toggle_menus() {
?>
<script type='text/javascript'>
jQuery(document).ready( function() {
/* add toggled-on class to submenus */
jQuery('.sub-menu').addClass('toggled-on');
});
</script>
<?php
}
add_action('wp_footer' , 'mod_toggle_menus'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, sub menu, dropdown, theme twenty fifteen"
} |
Running rmdir function on post save
How can I make wordpress call this function when a post is saved?
$folder = "/temp/files/"; //path of the folder to be removed
function delFolder($folder)
{
foreach(glob($folder . '/*') as $file) //takes the content of the given folder
{
if(is_dir($file)) //check if it is another folder then recursively call itself on it
delFolder($file);
else
unlink($file); //check if it is file then deletes it
}
rmdir($folder); //removes the folder
} | Add this to your theme's `functions.php` file:
function wpse202681_save_post_action($post_id, $post_object, $update) {
$folder = "/temp/files/";
delFolder($folder);
}
add_action( 'save_post', 'wpse202681_save_post_action', 10, 3 );
// + delFolder() function definition
You will probably have to alter folder paths depending on your `/temp/files/` location.
This will execute everytime any post is saved. You can restrict it to only some post type, etc. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, filesystem, wp filesystem"
} |
How to use oEmbeds on Post Content during AJAX requests
I have an AJAX request that returns a post. The `post_content` has links to Twitter, YouTube, TED and other platforms that are registered as oEmbed providers in a default, vanilla WordPress install. By now, the WordPress oEmbed handler does not register them and displays plain links and nothing else.
How can I fetch content via AJAX with oEmbed support? | Actually this was quite easy – when you know what's missing: The current post ID for the global `$wp_embed` object, so it knows what to refer to. The reason is simple: oEmbeds get cached as post meta data, so without knowing the ID, the MarkUp can't get fetched and replaced in the content.
// grab a post from the database
/** @var \WP_Embed $wp_embed */
global $wp_embed;
/** @var \WP_Post $post; */
// Add the fetched posts ID and add it to the global object
$wp_embed->post_ID = $post->ID;
// Execute the [embed] shortcode
$wp_embed->run_shortcode( $post->post_content );
// Execute the oEmbed handlers for plain links on the own line
$wp_embed->autoembed( $post->post_content );
That's it.
_Morein depth info about oEmbed and caching can be found in a related answer by @birgire._ | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "posts, ajax, oembed"
} |
How can I include properly javascript files in my wp plugin
I am creating a plugin for wordpress. And I want to know how can I include properly js in my plugin with correct path function. Thanks | you can use plugin_dir_url( **FILE** ) function to get the path of your js file. And enqueue script like this:-
add_action('wp_enqueue_scripts','ir_jscripts');
function ir_jscripts()
{
wp_enqueue_script( 'myscript',plugin_dir_url(__FILE__).'/jquery/script.js', array(), '3.3.5', true );
}
Thanks | stackexchange-wordpress | {
"answer_score": -2,
"question_score": -2,
"tags": "plugins, javascript"
} |
Favicon only appearing on the homepage?
I place my favico `favico.ico` on the root directory of my site.
Add the following code to `wp-content/themes/f2/header.php`:
<link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico" />
However, the favicon is ONLY appeared on the homepage? How can I make it effective on the whole site?
* * *
**EDIT:** I set the `href` as the abosolute path and it works, seeing below:
<link rel="shortcut icon" href=" /> | I set the href as the abosolute path and it works, seeing below:
<link rel="shortcut icon" href=" />
Or as suggested by @Caspar and @Howdy_McGee, for wordpress 4.3+, use:
`Dashboard -> Appearance -> Customize -> Site Identity -> Site Icon` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "favicon"
} |
Using WordPress gettext functions in a library outside plugin or theme scope
If I have a library available through packagist that could be used in WordPress plugin or theme development, how should I address multilanguage support if I have a few strings that could be localized?
I know that there has been some debate on composer usage in the WordPress world with very different views on it. (For example: 1, 2, 3)
But my question here is not about opinions on Composer in WordPress development, rather what would be the best practice to localize a library meant for WordPress which is not a plugin or theme. I would avoid making it a plugin, because it's not and it's not meant for end users. But just like many composer packages, as a development tool to be used in other projects.
Is it safe to use gettext wrappers provided by WordPress and meant for WordPress plugins/themes? That would save time but I'm not sure if this would work or create any trouble. | WordPress doesn't quite have a _practice_ of localizing something that isn't core/plugin/theme.
My educated guess would be that it will work just fine with same concepts, but you will have to write custom loading logic. Use lower level `load_textdomain()`, since higher level functions are meant for plugins/themes specifically.
As long as you determine and load domain translation correctly, WordPress wouldn't care that calls are coming from the library context. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, localization, l10n, composer, xgettext"
} |
Which template file to edit to edit homepage in Mystile
The homepage I'm using is not a static page, and I'm currently trying to add a content slider to it using master slider. I'm not too sure which file the homepage takes on as it's template, so I'm not sure where to put the PHP function for the slider.
What is the name of the template file that the homepage uses in Mystile? | The most likely file is index.php | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "functions, themes, templates, woocommerce offtopic"
} |
Localized version offers upgrade to en-us version
My Dutch 4.2.5 version offers to update to `WordPress 4.3.1–en_US` when I visit the dashboard.
I'm surprised that it does not offer an upgrade to something like `WordPress 4.3.1–nl_NL`
Will this work properly?
I do not remember how this went with earlier versions (i.e. what those offered).
[Edited to add]
Five minutes after posting this question a mail comes in which translates to: _Your site has been automatically updated to WordPress 4.2.5_. It is correct that automatic updates are on for this specific site.
What is going on? | (Answering my own question)
It is now 1 week after posting my question. I just revisited the dashboard. There are now two updates available: `WordPress 4.3.1–nl_NL` and `WordPress 4.3.1–en_US`.
So it looks as if the localized update takes some more time to prepare.
I will not click anything right now, assuming that the update will go automatically.
To be continued...
Added: Yes, the automatic update to the Dutch version came through... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "localization, upgrade"
} |
Fwd: [Website Name] Notice of Email Change
I got a reply from a user today with the following email below. I have never ran into this before. What causes this and how can it be stopped?
* * *
Hi username,
This notice confirms that your email was changed on website name.
If you did not change your email, please contact the Site Administrator at [email protected]
This email has been sent to [email protected]
Regards, | This is a feature since 4.3.0, as part of WordPress's improved security measures (check out the source on the WordPress code reference).
You can disable it with the following filter:
add_filter( 'send_email_change_email', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "email"
} |
printf - problem to understand code
I've recently build a plugin and used the code from this post right here: Create more Meta Boxes as needed
The Code works fine, but I dont understand the last parameter in the printf section.
if ( isset( $track['title'] ) || isset( $track['track'] ) ) {
printf( '<p>Song Title <input type="text" name="songs[%1$s][title]" value="%2$s" /> -- Track number : <input type="text" name="songs[%1$s][track]" value="%3$s" /><span class="remove">%4$s</span></p>', $c, $track['title'], $track['track'], __( 'Remove Track' ) );
$c = $c +1;
}
I dont get the last part, which is saying `__( 'Remove Track' )` could anyone explain this to me in detail?
Thanks in advance!!! | `__( 'Remove Track' )` is a translatable string. `__()`, `_e()`, `_x()`, ... all of them are gettext functions used by WordPress for language localization. It is missing the second parameter (optional), which is the textdomain, usually it should be:
__( 'Remove Track', 'your-plugin-text-domain' )
In that way, the string can be translated by your plugin without any conflict if the same string exists also in another plugin or in core.
You can get more details in I18n for WordPress Developers. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, php"
} |
Query All users that has post
I have this query so far :
$user_args = array(
'role' => 'frontend_vendor',
'orderby' => 'display_name',
'order' => 'ASC',
'number' => $no,
'offset' => $offset
);
$user_query = new WP_User_Query( $user_args );
Now what I want to do is to get all users that has only posts, i have an example query that i want to do. how do i do this with `wp_query()`?
SELECT users.id, posts.id
FROM wp_users
RIGHT JOIN wp_posts
ON wp_users.id = wp_posts.user_id
WHERE wp_posts.post_type = 'downloads'
AND wp_users.role = 'frontend_vendor'
ORDER BY display_name
ASC
LIMT 8
OFFEST 0
If the user has no posts, he should not be selected. | add this in your arguments `'query_id' => 'authors_with_posts',`
$user_args = array(
'role' => 'frontend_vendor',
'orderby' => 'display_name',
'query_id' => 'authors_with_posts',
'order' => 'ASC',
'number' => $no,
'offset' => $offset
); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "posts, query, users, mysql, join tables"
} |
To echo or not to echo?
Searching the code for related posts I found two almost identical code snippets, the only difference being that one uses echo:
echo '<li><a href="' . get_permalink() . '" title="' . the_title_attribute() . '">' . the_title() . '</a></li>';
and the other does not:
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>"> <h4><?php the_title() ?></h4></a>
</li>
Personally, I understand the second version (which mixes html with php) better, but I suspect, WP being what it is (always preferring php over html), that the first version may be the official way of doing things.
Is there are any preferred way of doing things in this case? And if yes why? | The main differences are: the first snippet has _html inside php_ while the second one has _php inside html_. Both approaches are basically valid, both are fine.
I would however always prefer (and recommend) to have _php inside html_ because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "php, html"
} |
WP Core hard coded to use http://www.w3.org/1999/xhtml not HTTPS
I've searched here and the WP Codex but haven't found anything.
I have recently added an SSL Cert to a client site. The front end is fine and there are no insecure elements.
However, the admin dashboard has lots of insecure elements. A simple search shows that there are about 20 files in both `wp-admin` and `wp-includes` that have the following link hard coded: <
There is no switch, as when using this config: `define('FORCE_SSL_ADMIN', true);`
I understand what this link is, and why it is needed. But I do not want to edit the core to force Admin to be secure.
Does anyone have any suggestions how I fix this? | There isn't a proper https/SSL variant of the link you have given, so probably, likely you are getting problems when enforcing it - no matter how you do it. I strongly assume that is the reason why the "unsecure" URL is used in the first place.
From comment:
> So does this mean it is impossible to have a truly secure dashboard?
Firstly I'd say, the URL you are talking about is more or less documentary. Secondly, if an external source is malicious, then it really doesn't matter if it is accessed via SSL or not. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, ssl"
} |
Getting entry ID from frm_email_message filter in formidable
Using the filter `frm_email_message` in formidable I want to change the message body in an email but I need to get the entry id.
I can get it using a different filter `frm_email_value`. Is there a way to store a value from one filter to use in another? | Not quite the exact answer but I used a `$_SESSION` to store the value instead. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "filters, hooks"
} |
Where is Customizer related data stored is the database?
How would I go about finding if a image (with a certain URL) is used stored in the Customizer data? | Theme mods are stored in the options table, one field per theme. Option name is `theme_mods_themename`, for instance `theme_mods_twentyfifteen`. | stackexchange-wordpress | {
"answer_score": 28,
"question_score": 17,
"tags": "theme customizer"
} |
Custom Post Type pages are "not found"
I've created two new Custom Post types using code that I've used successfully on other projects without issue. The first is called `top_charts`, the other `case_studies`, and both appear correctly in the admin menu and I can create new posts.
Unfortunately the new posts don't appear. I just get a `404.php` response.
I've created an `archive-top_charts.php` to see if I can get anything to appear, but I see a `404.php` "page not found" reply.
I originally named the custom posts `top-charts` and `case-studies`, but I thought the hyphen might have been the problem, and so renamed them to use an underscore instead. It hasn't helped.
I've tried re-saving my Permalinks, but nothing has changed. My .htaccess page looks like what you'd expect, too (and other pages works fine). What else can I check? | For fixing custom post not found please use below code in your `functions.php`:
flush_rewrite_rules( false );
You should only do this as a temporary measure otherwise it will run on every page load.
For more details please follow this link
As for the `archive-top_charts.php` not appearing, make sure you have `'has_archive' => true` when you're registering your post type. | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 26,
"tags": "custom post types, permalinks"
} |
Cookie settings for session across WPML subdomains using custom AJAX login
I am trying to enable a custom login session across both English and French subdomains.
-WordPress is installed only on domain.com.
-There are only en.domain.com and fr.domain.com as WPML subdomains, with redirects (as instructed here: <
-No issues with navigation across subdomains.
My AJAX custom login successfully signs in the user with wp_signon(). The AJAX request successfully returns 4 cookies. However, session is not initiated; on page refresh, user is still not connected.
When I login through /wp-login.php, the session is properly initiated.
It seems like the solution lies in the proper configuration of COOKIE_DOMAIN, COOKIEPATH & SITECOOKIEPATH settings:
define('COOKIE_DOMAIN', '.domain.com');
define('COOKIEPATH', '/');
define('SITECOOKIEPATH', '/');
Anyone has a solution for this? | I continued looking for an answer elsewhere, and found one.
Basically, the "cookie domain origin policy" was the issue, not sign-in process. I was calling domain.com/wp-admin/admin-ajax.php from a subdomain fr.domain.com.
I called fr.domain.com/wp-admin/admin-ajax.php instead, and that worked. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, subdomains, cookies"
} |
How to make a posttype show under a page hierarchy (example.com/page/posttype/entry)?
I have a page, say streets, which is a static page and has the slug `example.com/streets/`, and I want to have many single streets under it. Let these streets be called `streetdetails`, so a single street detail would be `example.com/streets/streetdetails/1`.
When I create a posttype with Custom Post UI, I always get just top level slugs, such as `example.com/streetdetails/1` and I cannot use the frontbase option either, as this is `blog` and will create false slugs.
How can I get that page -> posttype setup, that will put a posttype hierarchically under a page slug? | You need to alter your rewrite arguments in your `register_post_type()` call:
'rewrite' => array(
'slug' => 'streets/streetdetails',
'with_front' => false,
);
Make sure to re-save permalinks in the admin after making the code change. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, slug"
} |
Why doesn't the Media Browser use thumbnail sized images?
The folks updating our site oft complained about the media browser being very slow, so I went to have a look.
And, on the first load of the page, and when doing a search within the media browser, its taking a while to download each of the image previews, even longer than it should on our shonky office broadband.
So, I inspected the source of the page, and it became clear. Each image thumbnail is actually linking to the full size image, and resizing it in HTML, see:
![enter image description here](
Is this an issue anyone's aware of? Is there a workaround? I'd presume there should be a _built in_ thumbnail type for that purpose. | As per the comments, my theme was missing the system default `medium` image size.
Applying @birgire's workaround to make the system use a custom size did the trick. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, post thumbnails, media, bug"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.