qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
248,787 | <p>I made a short code in my plugin that pulls out one of the custom post featured image from one taxonomy term each, the taxonomy term under which the post is in, and two term metas.</p>
<p>I want the term of that taxonomy to be limited to only a certain number of characters e.g. 12 but my code below does not truncate the long name of that term and add an ellipses as i am trying below.</p>
<pre><code>ob_start();
$post_type = 'esitykset';
$taxonomy = 'tapahtumat';
$post_ids = get_unique_term_recent_posts( $post_type, $taxonomy );
if ( $post_ids ) {
$args = [
'post__in' => $post_ids,
'post_type' => $post_type,
'posts_per_page' => 8
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<div class="home-poster-column">
<?php
$thumb = '';
$width = (int) apply_filters( 'et_pb_index_blog_image_width', 724 );
$height = (int) apply_filters( 'et_pb_index_blog_image_height', 1024 );
$classtext = 'et_pb_post_main_image';
$titletext = get_the_title();
$thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
$thumb = $thumbnail["thumb"];
?>
<?php
global $term_link;
if ( $terms = get_the_terms( $term_link->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
}
?>
<a href="<?php echo get_term_link( $term ); ?>">
<span class="esitys-poster">
<?php print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height ); ?>
</span><br/>
<strong>
<?php
$event = the_terms( $post->ID, 'tapahtumat');
$len = 10; // <-- Adjust to your needs!
echo mb_strimwidth($event, 0, $len, 'UTF8' ) . '&hellip;';
?>
</strong> <br/>
<?php
/*
Get the date range meta of tapahtumat taxonomy
http://wordpress.stackexchange.com/questions/11820/echo-custom-taxonomy-field-values-outside-the-loop
*/
global $date_range;
if ( $terms = get_the_terms( $date_range->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'date-range', true ) . '<br/>';
}
/* Get the start price meta of tapahtumat taxonomy */
global $start_price;
if ( $terms = get_the_terms( $start_price->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'start-price', true );
}
?>
</a>
</div>
<?php
wp_reset_postdata(); } // endif have_posts()
} // endif $post_ids
$myvariable = ob_get_clean();
return $myvariable;
</code></pre>
<p>I know that the code above is a little twisted. Please feel free to suggest better ways if you feel is better approach.</p>
<p>Thanks</p>
| [
{
"answer_id": 248791,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>This is not working because <code>the_terms()</code> is echo-ing the output.</p>\n\n<p>It would make more sen... | 2016/12/09 | [
"https://wordpress.stackexchange.com/questions/248787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77779/"
] | I made a short code in my plugin that pulls out one of the custom post featured image from one taxonomy term each, the taxonomy term under which the post is in, and two term metas.
I want the term of that taxonomy to be limited to only a certain number of characters e.g. 12 but my code below does not truncate the long name of that term and add an ellipses as i am trying below.
```
ob_start();
$post_type = 'esitykset';
$taxonomy = 'tapahtumat';
$post_ids = get_unique_term_recent_posts( $post_type, $taxonomy );
if ( $post_ids ) {
$args = [
'post__in' => $post_ids,
'post_type' => $post_type,
'posts_per_page' => 8
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<div class="home-poster-column">
<?php
$thumb = '';
$width = (int) apply_filters( 'et_pb_index_blog_image_width', 724 );
$height = (int) apply_filters( 'et_pb_index_blog_image_height', 1024 );
$classtext = 'et_pb_post_main_image';
$titletext = get_the_title();
$thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
$thumb = $thumbnail["thumb"];
?>
<?php
global $term_link;
if ( $terms = get_the_terms( $term_link->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
}
?>
<a href="<?php echo get_term_link( $term ); ?>">
<span class="esitys-poster">
<?php print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height ); ?>
</span><br/>
<strong>
<?php
$event = the_terms( $post->ID, 'tapahtumat');
$len = 10; // <-- Adjust to your needs!
echo mb_strimwidth($event, 0, $len, 'UTF8' ) . '…';
?>
</strong> <br/>
<?php
/*
Get the date range meta of tapahtumat taxonomy
http://wordpress.stackexchange.com/questions/11820/echo-custom-taxonomy-field-values-outside-the-loop
*/
global $date_range;
if ( $terms = get_the_terms( $date_range->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'date-range', true ) . '<br/>';
}
/* Get the start price meta of tapahtumat taxonomy */
global $start_price;
if ( $terms = get_the_terms( $start_price->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'start-price', true );
}
?>
</a>
</div>
<?php
wp_reset_postdata(); } // endif have_posts()
} // endif $post_ids
$myvariable = ob_get_clean();
return $myvariable;
```
I know that the code above is a little twisted. Please feel free to suggest better ways if you feel is better approach.
Thanks | This is not working because `the_terms()` is echo-ing the output.
It would make more sense to trim down the lengthy term names, instead of doing it directly on the HTML output of `get_the_term_list()` that's used by `get_the_terms()`. That could give unvalid HTML, that could break the layout of your site.
Here's an example for the corresponding theme file:
```
// Add a filter
add_filter( 'get_the_terms', 'wpse248787_get_the_terms' );
// Display terms
the_terms( get_the_ID(), 'tapahtumat' );
// Remove the filter again
remove_filter( 'get_the_terms', 'wpse248787_get_the_terms' );
```
where you have defined:
```
function wpse248787_get_the_terms( $terms )
{
$len = 10; // <-- Adjust to your needs!
// Limit term names if needed
foreach( $terms as $term )
{
if( $len > 0 && $len < mb_strlen( $term->name ) )
$term->name = mb_substr( $term->name, 0, $len - 1, 'UTF8' ) . '…';
}
return $terms;
}
```
in the `functions.php` file in the current theme directory. You might also need to addjust the encoding argument or use e.g. `get_option( 'blog_charset' )`. |
248,814 | <p>I know it's easy to disable Wordpress from adding both <code>p</code> and <code>br</code> tags with:</p>
<pre><code>remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
</code></pre>
<p>but I want Wordpress to keep adding <code><br></code> where there is a line break.
I only use text editor, visual editor is disabled.
It was working fine until the recent update to Wordpress 4.7 - now it is adding some closing <code>p</code> tags, without opening them like <code></p></code> .</p>
<p>even tried <a href="https://wordpress.org/plugins/disable-automatic-p-tags/" rel="nofollow noreferrer">this</a> plugin but it disables br tags as well.</p>
<p>Any way of just disabling <code>p</code> tags not <code>br</code> tags in post content? I can't find anything on the internet that says something about a solution.</p>
| [
{
"answer_id": 252582,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 0,
"selected": false,
"text": "<p>The \"the_content\" filter is used to filter the content of the post where filter function in <code>your_prefix_... | 2016/12/09 | [
"https://wordpress.stackexchange.com/questions/248814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6927/"
] | I know it's easy to disable Wordpress from adding both `p` and `br` tags with:
```
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
```
but I want Wordpress to keep adding `<br>` where there is a line break.
I only use text editor, visual editor is disabled.
It was working fine until the recent update to Wordpress 4.7 - now it is adding some closing `p` tags, without opening them like `</p>` .
even tried [this](https://wordpress.org/plugins/disable-automatic-p-tags/) plugin but it disables br tags as well.
Any way of just disabling `p` tags not `br` tags in post content? I can't find anything on the internet that says something about a solution. | You'd better never disable those actions (what you say). Instead, insert `add_filter('the_content', 'MyFilter', 88 );` and create such function:
```
function MyFilter($content){
$tags = array( 'p', 'span');
///////////////////////////////////////////////////
///////// HERE INSERT ANY OF BELOW CODE //////////
///////////////////////////////////////////////////
return $content;
}
```
======== METHOD 1 =========
===========================
```
$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);
$content= preg_replace( '#<\/(' . implode( '|', $tags) . ')>#si', '', $content);
```
======== METHOD 2 ======
========================
```
foreach ($tags as $tag) {
$content= preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content);
}
```
======== METHOD 3 =========
===========================
**DOM** object (preferred): <https://stackoverflow.com/a/31380542/2377343> |
248,826 | <p>How can I use <code>.htaccess</code> to rewrite a a page on a subdomain to a page on the parent? (E.g. people visiting mysite.com/landingpage will see the content from dev.mysite.com/landingpage)?</p>
<p>Ive been working to redesign a WordPress site, using a dev.mysite.com subdomain. The site isn't ready to replace the live WP site yet (mysite.com) but I need to map one of the pages to the old domain and make it public. Since all the work (template,database,etc) is on the subdomain, I can't just import the page to the old domain, so I seemingly need to use <code>mod_rewrite</code>, which is way beyond my skill level.
Also, since its two different WP Installations (not multisite), would I use the domain <code>.htaccess</code> file or the subdomain <code>.htaccess</code> file?</p>
<p>Thanks!</p>
| [
{
"answer_id": 252582,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 0,
"selected": false,
"text": "<p>The \"the_content\" filter is used to filter the content of the post where filter function in <code>your_prefix_... | 2016/12/09 | [
"https://wordpress.stackexchange.com/questions/248826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68512/"
] | How can I use `.htaccess` to rewrite a a page on a subdomain to a page on the parent? (E.g. people visiting mysite.com/landingpage will see the content from dev.mysite.com/landingpage)?
Ive been working to redesign a WordPress site, using a dev.mysite.com subdomain. The site isn't ready to replace the live WP site yet (mysite.com) but I need to map one of the pages to the old domain and make it public. Since all the work (template,database,etc) is on the subdomain, I can't just import the page to the old domain, so I seemingly need to use `mod_rewrite`, which is way beyond my skill level.
Also, since its two different WP Installations (not multisite), would I use the domain `.htaccess` file or the subdomain `.htaccess` file?
Thanks! | You'd better never disable those actions (what you say). Instead, insert `add_filter('the_content', 'MyFilter', 88 );` and create such function:
```
function MyFilter($content){
$tags = array( 'p', 'span');
///////////////////////////////////////////////////
///////// HERE INSERT ANY OF BELOW CODE //////////
///////////////////////////////////////////////////
return $content;
}
```
======== METHOD 1 =========
===========================
```
$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);
$content= preg_replace( '#<\/(' . implode( '|', $tags) . ')>#si', '', $content);
```
======== METHOD 2 ======
========================
```
foreach ($tags as $tag) {
$content= preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content);
}
```
======== METHOD 3 =========
===========================
**DOM** object (preferred): <https://stackoverflow.com/a/31380542/2377343> |
248,840 | <p>I tried to update Wordpress to version 4.7 and received a fatal error. I'm using windows and XAMPP for localhost development.</p>
<pre><code>Update WordPress
Downloading update from
https://downloads.wordpress.org/release/wordpress-4.7-new-bundled.zip…
Unpacking the update…
Fatal error: Maximum execution time of 30 seconds exceeded in
<path to project>\wp-admin\includes\class-wp-filesystem-direct.php on line 81
</code></pre>
<p>Inside class-wp-file-system-direct.php (line 81 is if-statement):</p>
<pre><code>public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp )
return false;
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) // LINE 81
return false;
$this->chmod( $file, $mode );
return true;
}
</code></pre>
<p>I removed read-only permissions from the includes folder and the file itself and explicitly allowed write permission on the file. I ran the auto update for Wordpress again, and now I'm getting.</p>
<pre><code>Update WordPress
Another update is currently in progress.
</code></pre>
<p>Not sure what to try next.</p>
<p><strong>Solved</strong></p>
<p>Manually updating Wordpress solved the problem.</p>
| [
{
"answer_id": 248872,
"author": "nu everest",
"author_id": 106850,
"author_profile": "https://wordpress.stackexchange.com/users/106850",
"pm_score": 2,
"selected": true,
"text": "<p><strong>Manually updating Wordpress fixes this issue.</strong> </p>\n\n<p><strong><em>Upgrading WordPress... | 2016/12/09 | [
"https://wordpress.stackexchange.com/questions/248840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106850/"
] | I tried to update Wordpress to version 4.7 and received a fatal error. I'm using windows and XAMPP for localhost development.
```
Update WordPress
Downloading update from
https://downloads.wordpress.org/release/wordpress-4.7-new-bundled.zip…
Unpacking the update…
Fatal error: Maximum execution time of 30 seconds exceeded in
<path to project>\wp-admin\includes\class-wp-filesystem-direct.php on line 81
```
Inside class-wp-file-system-direct.php (line 81 is if-statement):
```
public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp )
return false;
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) // LINE 81
return false;
$this->chmod( $file, $mode );
return true;
}
```
I removed read-only permissions from the includes folder and the file itself and explicitly allowed write permission on the file. I ran the auto update for Wordpress again, and now I'm getting.
```
Update WordPress
Another update is currently in progress.
```
Not sure what to try next.
**Solved**
Manually updating Wordpress solved the problem. | **Manually updating Wordpress fixes this issue.**
***Upgrading WordPress Core Manually (How To)*** [WordFence Reference](https://www.wordfence.com/learn/how-to-manually-upgrade-wordpress-themes-and-plugins/)
* First create a full backup of your website. This is very important in
case you make a mistake.
* Download the newest WordPress ZIP file from wordpress.org. Unzip the
file into a directory on your local machine or in a separate
directory on your website.
* Deactivate all of the plugins on your WordPress site.
* Go to your website root directory and delete your ‘wp-includes’ and
‘wp-admin’ directories. You can do this via sFTP or via SSH.
* Upload (or copy over) the new wp-includes and wp-admin directories
from the new version of WordPress you unzipped to your website root
directory to replace the directories you just deleted.
* Don’t delete your wp-content directory or any of the files in that
directory. Copy over the files from the wp-content directory in the
new version of WordPress to your existing wp-content directory. You
will overwrite any existing files with the same name. All of your
other files in wp-content will remain in place.
* Copy all files from the root (‘/’) directory of the new version of
WordPress that you unzipped into your website root directory (or the
root directory of your WordPress installation). You will overwrite
any existing files and new files will also be copied across. Your
wp-config.php file will not be affected because WordPress is never
distributed with a wp-config.php file.
* Examine the wp-config-sample.php which is distributed with WordPress
to see if any new settings have been added that you may want to use
or modify.
* If you are upgrading manually after a failed auto-update, remove the
.maintenance file from your WordPress root directory. This will
remove the ‘failed update’ message from your site.
* Visit your main WordPress admin page at /wp-admin/ where you may be
asked to sign-in again. You may also have to upgrade your database
and will be prompted if this is needed. If you can’t sign-in, try
clearing your cookies. Re-enable your plugins which you disabled
earlier.
* Clear your browser cache to ensure you can see all changes. If you
are using a front-end cache like ‘varnish’ you should also clear that
to ensure that your customers can see the newest changes on your
site.
* Your upgrade is now complete and you should be running the newest
version of WordPress. |
248,851 | <p>I have allow readers to select the posts order with different parameters. For a example users can order posts by "vote". (Vote is a custom post type.) </p>
<p>Then URL will be <code>http://example.com/?sort_by_type=vote</code></p>
<p>I have used <code>pre_get_posts</code> action to do orderthe posts. It works fine. The problem is pagination .</p>
<p>Pagination look like this in my theme.</p>
<pre><code>http://example.com/?sort_by_type=vote/page/2/
</code></pre>
<p>But it should be <code>http://example.com/page/2/?sort_by_type=vote</code> to work correctly. </p>
<p>So how I correct pagination?</p>
<hr>
<p>Edit After comment of @govind : The theme which I used is a not a theme developed by me. What I did i, if URL contain <code>?sort_by_type=vote</code> request I changed the post order using <code>pre_get_posts</code> filter.</p>
<p>When I cheeking theme I found following code. </p>
<pre><code><?php if ( is_home() || is_archive() || is_search() ) : // If viewing the blog, an archive, or search results. ?>
<?php loop_pagination(
array(
'prev_text' => _x( '&larr; Previous', 'posts navigation', 'daily' ),
'next_text' => _x( 'Next &rarr;', 'posts navigation', 'daily' )
)
); ?>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 248852,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>You should define a new pagination function for do it.</p>\n\n<pre><code><?php\nfunction custom_pa... | 2016/12/10 | [
"https://wordpress.stackexchange.com/questions/248851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106350/"
] | I have allow readers to select the posts order with different parameters. For a example users can order posts by "vote". (Vote is a custom post type.)
Then URL will be `http://example.com/?sort_by_type=vote`
I have used `pre_get_posts` action to do orderthe posts. It works fine. The problem is pagination .
Pagination look like this in my theme.
```
http://example.com/?sort_by_type=vote/page/2/
```
But it should be `http://example.com/page/2/?sort_by_type=vote` to work correctly.
So how I correct pagination?
---
Edit After comment of @govind : The theme which I used is a not a theme developed by me. What I did i, if URL contain `?sort_by_type=vote` request I changed the post order using `pre_get_posts` filter.
When I cheeking theme I found following code.
```
<?php if ( is_home() || is_archive() || is_search() ) : // If viewing the blog, an archive, or search results. ?>
<?php loop_pagination(
array(
'prev_text' => _x( '← Previous', 'posts navigation', 'daily' ),
'next_text' => _x( 'Next →', 'posts navigation', 'daily' )
)
); ?>
<?php endif; ?>
``` | You can create your custom pagination using `paginate_link()` function and add custom query string after current url.
To add argument to the links of paginations you can pass them as array argument inside the 'add\_args'
```
if ( is_home() || is_archive() || is_search() ) :
echo paginate_links(array(
'base' => preg_replace('/\?.*/', '/', get_pagenum_link(1)) . '%_%',
'current' => max(1, get_query_var('paged')),
'format' => 'page/%#%',
'total' => $wp_query->max_num_pages,
// here you can pass custom query string to the pagination url
'add_args' => array(
'sort_by_type' => ( !empty($_GET['sort_by_type']) ) ? $_GET['sort_by_type'] : 'vote'
)
));
endif;
```
Replace your pagination code with this above code.
It will print all string with custom query string.
`http://example.com/page/2/?sort_by_type=vote`
Hope this help! |
248,877 | <p>How do I add the date before the entry title in Twenty Twelve with just functions.php?</p>
<p>Right now I have to add and modify many files in the child theme such as content.php, content-aside.php, content-image.php, content-link.php, content-quote.php, content-status.php. </p>
<p>Is there a way to do it with filters? I tried to put it in the_content but the date displays below the title. </p>
| [
{
"answer_id": 248878,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>the_title</code> filter. Example below.</p>\n\n<pre><code>function display_extra_title( $titl... | 2016/12/10 | [
"https://wordpress.stackexchange.com/questions/248877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87509/"
] | How do I add the date before the entry title in Twenty Twelve with just functions.php?
Right now I have to add and modify many files in the child theme such as content.php, content-aside.php, content-image.php, content-link.php, content-quote.php, content-status.php.
Is there a way to do it with filters? I tried to put it in the\_content but the date displays below the title. | Base on @Tunji answer.
You can add some conditions to the function to detect home-page, feeds...
```
function display_extra_title( $title, $id = null ) {
$date = the_date('', '', '', false);
if(is_home()){
$title = get_bloginfo( 'name' );
return $date . $title;
}
else{
return $date . $title;
}
}
add_filter( 'the_title', 'display_extra_title', 10, 2 );
```
In order to properly return `the_date` and not echoing it, you must set the last parameter to false. See more details [here](https://codex.wordpress.org/Function_Reference/the_date)
If you don't want to display the date in the menu widget... You can surround `$date` in a span and add css to not display it when it's the menu, sidebar...
```
$title = '<span class="title_date">'.$date.'</span> '.$title;
```
In the css (adjust and add all what you need:
```
.sidebar .title_date{ display:none;}
``` |
248,900 | <p>I have successfully translated a child theme, but not the same result in mu-plugins folder.</p>
<p>The name of the plugin is "mu-functions.php".
In this file I have added the "Text Domain: mu-functions" in the header and then I have loaded the textdomain:</p>
<pre><code>add_action( 'plugins_loaded', 'myplugin_muload_textdomain' );
function myplugin_muload_textdomain() {
load_muplugin_textdomain( 'mu-functions', basename( dirname(__FILE__) ) . '/inc/languages' );
}
</code></pre>
<p>The structure of the plugin that I have created in the mu-plugins directory is the following:</p>
<p>In the same directory I have a "inc"(include) folder where I put all the other files that are being called through the "include_once()" function in "mu-function.php" file.
Along with this files, in the same "inc" folder directory, I have the "languages" folder where I have created the "mu-functions.pot" file that has been translated to Portuguese and then generated to both ".mo" and ".po" files.</p>
<p>In my child theme I had an issue with these ".mo" and ".po" files. I have found in another forum that I had to name them only by the locale (so in this case "pt_PT") and not "Text-Domain-pt_PT". This issue has been successfully solved.
Being so, for testing purposes I have generated 2 more other ".mo" and ".po" files.
These are the files that are in my languages folder:</p>
<ul>
<li>mu-functions-pt_PT.mo</li>
<li>mu-functions-pt_PT.po</li>
<li>mu-functions.pot</li>
<li>pt_PT.mo</li>
<li>pt_PT.po</li>
</ul>
<p>Can anybody, please, help me? What am I missing?</p>
| [
{
"answer_id": 248887,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 6,
"selected": true,
"text": "<p>4.7 has it enabled by default. The easy way to check if it is working is just to visit the example.com/wp-... | 2016/12/10 | [
"https://wordpress.stackexchange.com/questions/248900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108695/"
] | I have successfully translated a child theme, but not the same result in mu-plugins folder.
The name of the plugin is "mu-functions.php".
In this file I have added the "Text Domain: mu-functions" in the header and then I have loaded the textdomain:
```
add_action( 'plugins_loaded', 'myplugin_muload_textdomain' );
function myplugin_muload_textdomain() {
load_muplugin_textdomain( 'mu-functions', basename( dirname(__FILE__) ) . '/inc/languages' );
}
```
The structure of the plugin that I have created in the mu-plugins directory is the following:
In the same directory I have a "inc"(include) folder where I put all the other files that are being called through the "include\_once()" function in "mu-function.php" file.
Along with this files, in the same "inc" folder directory, I have the "languages" folder where I have created the "mu-functions.pot" file that has been translated to Portuguese and then generated to both ".mo" and ".po" files.
In my child theme I had an issue with these ".mo" and ".po" files. I have found in another forum that I had to name them only by the locale (so in this case "pt\_PT") and not "Text-Domain-pt\_PT". This issue has been successfully solved.
Being so, for testing purposes I have generated 2 more other ".mo" and ".po" files.
These are the files that are in my languages folder:
* mu-functions-pt\_PT.mo
* mu-functions-pt\_PT.po
* mu-functions.pot
* pt\_PT.mo
* pt\_PT.po
Can anybody, please, help me? What am I missing? | 4.7 has it enabled by default. The easy way to check if it is working is just to visit the example.com/wp-json url, and you should get a list of registered end points there
There is no official option to disable it as (at least there was a talk about it not sure if it got in the release), some core functionality depends on it.
The most obvious things to check for if it is not working is your htaccess rules, and do you have a wp-json directory
Also, if `/wp-json/wp/v2/posts` type URLs don't work for you, but `/?rest_route=/wp-json/wp/v2/posts` does, it means you need to enable pretty permalinks in the settings (suggested by Giles Butler in comments below). |
248,904 | <p>I'm new at this.</p>
<p>I need a shortcode that returns the post id of the post in which the shortcode is inserted.</p>
<p>If someone could provide that it would open the doors of understanding for me :)</p>
<p>Much appreciated!</p>
| [
{
"answer_id": 248907,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 4,
"selected": true,
"text": "<p>Place the below code to your themes <code>functions.php</code> or inside your plugin and the <code>[return_... | 2016/12/11 | [
"https://wordpress.stackexchange.com/questions/248904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108215/"
] | I'm new at this.
I need a shortcode that returns the post id of the post in which the shortcode is inserted.
If someone could provide that it would open the doors of understanding for me :)
Much appreciated! | Place the below code to your themes `functions.php` or inside your plugin and the `[return_post_id]` shortcode will print the post ID.
```
add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );
function the_dramatist_return_post_id() {
return get_the_ID();
}
```
Hope that helps. |
248,957 | <p>This is my code in functions.php for adding the custom field in comment form</p>
<pre><code>add_filter( 'comment_form_default_fields', 'add_phonenumber_field' );
function add_phonenumber_field($fields) {
$fields['phonenumber'] = '<p class="comment-form-phonenumber"><label for="phonenumber">Phone Number <span class="required">*</span></label>' .
'<input id="phone-number" name="phone-number" type="tel" pattern="[\+]\d{2}[\(]\d{3}[\)]\d{3}[\-]\d{4}" title="Phone Number (Format: +63(123)456-7980)" aria-required="true" required="required"/></p>';
return $fields;
}
</code></pre>
<p>This is how comment form looks like now
<a href="https://i.stack.imgur.com/h6uOO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h6uOO.png" alt="enter image description here"></a></p>
<p>But when I send the comment and click edit in the Dashboard under Comments tab, no phone number field is there.
<a href="https://i.stack.imgur.com/7UTKg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UTKg.png" alt="enter image description here"></a></p>
<p>How can I make it appear in when I edit the comment and display it in the approved comments on the front-end?
Thanks for help!</p>
| [
{
"answer_id": 248907,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 4,
"selected": true,
"text": "<p>Place the below code to your themes <code>functions.php</code> or inside your plugin and the <code>[return_... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90228/"
] | This is my code in functions.php for adding the custom field in comment form
```
add_filter( 'comment_form_default_fields', 'add_phonenumber_field' );
function add_phonenumber_field($fields) {
$fields['phonenumber'] = '<p class="comment-form-phonenumber"><label for="phonenumber">Phone Number <span class="required">*</span></label>' .
'<input id="phone-number" name="phone-number" type="tel" pattern="[\+]\d{2}[\(]\d{3}[\)]\d{3}[\-]\d{4}" title="Phone Number (Format: +63(123)456-7980)" aria-required="true" required="required"/></p>';
return $fields;
}
```
This is how comment form looks like now
[](https://i.stack.imgur.com/h6uOO.png)
But when I send the comment and click edit in the Dashboard under Comments tab, no phone number field is there.
[](https://i.stack.imgur.com/7UTKg.png)
How can I make it appear in when I edit the comment and display it in the approved comments on the front-end?
Thanks for help! | Place the below code to your themes `functions.php` or inside your plugin and the `[return_post_id]` shortcode will print the post ID.
```
add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );
function the_dramatist_return_post_id() {
return get_the_ID();
}
```
Hope that helps. |
248,967 | <p>We can get posts from a category using below request</p>
<pre><code> `/wp/v2/posts?categories=1&search=somequery`
</code></pre>
<p>It only gives results from category(1) only. How can we get results from category(1) and from all subcategories of category(1) also? Than You.</p>
| [
{
"answer_id": 248972,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 0,
"selected": false,
"text": "<p>You'll need to do an additional call to find the IDs of the subcategories – there is no way to get posts from su... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107444/"
] | We can get posts from a category using below request
```
`/wp/v2/posts?categories=1&search=somequery`
```
It only gives results from category(1) only. How can we get results from category(1) and from all subcategories of category(1) also? Than You. | This answer has what you want <https://wordpress.stackexchange.com/a/314152/49962>
WP already does this out of the box thanks to the include\_children parameter of tax\_query which is true by default.
So you do not need to tell it the sub-terms, just do something like this:
```
/wp/v2/posts?categories=1
```
Where `categories=1` is the parent category ID |
248,983 | <p>I'm using the following form html to generate a search function on a wordpress site:</p>
<pre><code><form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<button type="submit">Search</button>
</fieldset>
</form>
</code></pre>
<p>It works ok, but I wish to only return results for a specific custom post type. I'm using the search.php template from twentysixteen theme which contains this:</p>
<pre><code><?php global $wp_query; ?>
<h1 class="search-title"><?php echo $wp_query->found_posts; ?> Results found for: <span><?php the_search_query(); ?></span></h1>
<?php if ( have_posts() ) { ?>
<ul class="results">
<?php while ( have_posts() ) { the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
<div class="post-content">
<h3><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php echo substr(get_the_excerpt(), 0,140); ?>... <a href="<?php the_permalink(); ?>">Read More</a></p>
</div>
</li>
<?php } ?>
</ul>
<?php } ?>
</code></pre>
<p>Is there a variable that I can add somewhere to only return results for a specific post type? Thanks</p>
| [
{
"answer_id": 248984,
"author": "The Sumo",
"author_id": 76021,
"author_profile": "https://wordpress.stackexchange.com/users/76021",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden i... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76021/"
] | I'm using the following form html to generate a search function on a wordpress site:
```
<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search…" maxlength="50" required="required" />
<button type="submit">Search</button>
</fieldset>
</form>
```
It works ok, but I wish to only return results for a specific custom post type. I'm using the search.php template from twentysixteen theme which contains this:
```
<?php global $wp_query; ?>
<h1 class="search-title"><?php echo $wp_query->found_posts; ?> Results found for: <span><?php the_search_query(); ?></span></h1>
<?php if ( have_posts() ) { ?>
<ul class="results">
<?php while ( have_posts() ) { the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
<div class="post-content">
<h3><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php echo substr(get_the_excerpt(), 0,140); ?>... <a href="<?php the_permalink(); ?>">Read More</a></p>
</div>
</li>
<?php } ?>
</ul>
<?php } ?>
```
Is there a variable that I can add somewhere to only return results for a specific post type? Thanks | Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:
```
<form class="search" action="<?php echo home_url( '/' ); ?>">
<input type="search" name="s" placeholder="Search…">
<input type="submit" value="Search">
<input type="hidden" name="post_type" value="custom-post-type">
</form>
```
Obviously you will need to replace the value "custom-post-type" with your own custom post type. |
248,991 | <p>I'm making a plugin where the user can order something. But before he has to confirm his email, so I'm sending out that mail with the confirmation link, something like that: <code>mydomain.com/myconfirmation?token=MYTOKEN</code></p>
<p>How do I fetch this confirmation url <code>myconfirmation</code> in WordPress without the website owner having to create an extra page for this?</p>
| [
{
"answer_id": 248984,
"author": "The Sumo",
"author_id": 76021,
"author_profile": "https://wordpress.stackexchange.com/users/76021",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden i... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248991",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92649/"
] | I'm making a plugin where the user can order something. But before he has to confirm his email, so I'm sending out that mail with the confirmation link, something like that: `mydomain.com/myconfirmation?token=MYTOKEN`
How do I fetch this confirmation url `myconfirmation` in WordPress without the website owner having to create an extra page for this? | Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:
```
<form class="search" action="<?php echo home_url( '/' ); ?>">
<input type="search" name="s" placeholder="Search…">
<input type="submit" value="Search">
<input type="hidden" name="post_type" value="custom-post-type">
</form>
```
Obviously you will need to replace the value "custom-post-type" with your own custom post type. |
248,993 | <p>I would like to order a list of post title alphabetically.
I am using this specific query </p>
<pre><code>// WP_Query arguments
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<ul><li style="float:left; width:100%;"><a href="'.get_the_permalink().'" style="color:#D34D3D">'.get_the_title().'</a></li></ul>';
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
</code></pre>
<p>The query worked perfect until a certain point of the list where the order seems to be messed up. </p>
<p>Why the order doesn't work correctly for all the post title? </p>
| [
{
"answer_id": 249002,
"author": "tormorten",
"author_id": 49832,
"author_profile": "https://wordpress.stackexchange.com/users/49832",
"pm_score": 2,
"selected": false,
"text": "<p>Try adding <code>'suppress_filters' => true</code> to your query args. Maybe you have a plugin that modi... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248993",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103072/"
] | I would like to order a list of post title alphabetically.
I am using this specific query
```
// WP_Query arguments
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<ul><li style="float:left; width:100%;"><a href="'.get_the_permalink().'" style="color:#D34D3D">'.get_the_title().'</a></li></ul>';
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
```
The query worked perfect until a certain point of the list where the order seems to be messed up.
Why the order doesn't work correctly for all the post title? | Try adding `'suppress_filters' => true` to your query args. Maybe you have a plugin that modifies the queries.
You could also check if the posts out of order (the first one) is a sticky post. Sticky posts by default skip the order queue.
You can disable this by adding `'ignore_sticky_posts' => true` to your query args. |
248,998 | <p>This is the code below I am using to create a table when installing plugin. But, I tried many ways and for some reason it is not working. Is there any other efficient way of doing this? Please Help, thanks in Advanced</p>
<pre><code>global $wpdb;
function creating_order_tables() {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
echo "hello";
}
}
register_activation_hook(__FILE__, 'creating_order_tables');
</code></pre>
| [
{
"answer_id": 248999,
"author": "Kamaro",
"author_id": 108796,
"author_profile": "https://wordpress.stackexchange.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "<p>Try this one, Also remember int can have maximum of int(11)</p>\n\n<pre><code><?php\nglobal $wpdb;\n\n// ... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/248998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] | This is the code below I am using to create a table when installing plugin. But, I tried many ways and for some reason it is not working. Is there any other efficient way of doing this? Please Help, thanks in Advanced
```
global $wpdb;
function creating_order_tables() {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
echo "hello";
}
}
register_activation_hook(__FILE__, 'creating_order_tables');
``` | Try using a different method. WordPress fires a hook during plugin activation `activate_yourplugin/filename.php`. You can use this to create tables.
```
function creating_order_tables() {
if(!get_option('tables_created', false)) {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
if(!function_exists('dbDelta')) {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}
dbDelta($sql);
echo "Tables created...";
update_option('tables_created', true);
}
}
}
add_action('activate_yourplugin/yourplugin.php', 'creating_order_tables');
``` |
249,003 | <p>I'm using the <code>WP_Customize_Cropped_Image_Control</code> for the user to upload and crop an image in the Customizer. However, the get theme mod function doesn't seem to be working for outputting it as I usually do.</p>
<p>This is what I have in my customizer.php file:</p>
<pre><code>$wp_customize->add_setting( 'bio_image', array(
'default' => get_template_directory_uri() . '/images/default.jpg',
'transport' => 'postMessage'
) );
$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'bio_image', array(
'label' => __( 'bio_image', 'myTheme' ),
'flex_width' => false,
'flex_height' => false,
'width' => 200,
'height' => 200,
'settings' => 'bio_image',
) ) );
</code></pre>
<p>This is what I have in my template file:</p>
<pre><code><img src="<?php echo get_theme_mod( 'bio_image' , get_template_directory_uri().'/images/default.jpg' ); ?>">
</code></pre>
<p>This only displays the <code>default.jpg</code> image, and at the wrong dimensions.</p>
<p>Is there another way of outputting the cropped image?</p>
| [
{
"answer_id": 249006,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 0,
"selected": false,
"text": "<p>This did it for me, simplifying <a href=\"https://wordpress.stackexchange.com/users/8521/weston-ruter\... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/249003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] | I'm using the `WP_Customize_Cropped_Image_Control` for the user to upload and crop an image in the Customizer. However, the get theme mod function doesn't seem to be working for outputting it as I usually do.
This is what I have in my customizer.php file:
```
$wp_customize->add_setting( 'bio_image', array(
'default' => get_template_directory_uri() . '/images/default.jpg',
'transport' => 'postMessage'
) );
$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'bio_image', array(
'label' => __( 'bio_image', 'myTheme' ),
'flex_width' => false,
'flex_height' => false,
'width' => 200,
'height' => 200,
'settings' => 'bio_image',
) ) );
```
This is what I have in my template file:
```
<img src="<?php echo get_theme_mod( 'bio_image' , get_template_directory_uri().'/images/default.jpg' ); ?>">
```
This only displays the `default.jpg` image, and at the wrong dimensions.
Is there another way of outputting the cropped image? | The theme mod here is storing the attachment post ID whereas your default value is a URL. So what you'd need to do is something like:
```
<?php
function get_bio_image_url() {
if ( get_theme_mod( 'bio_image' ) > 0 ) {
return wp_get_attachment_url( get_theme_mod( 'bio_image' ) );
} else {
return get_template_directory_uri() . '/images/default.jpg';
}
}
?>
<img src="<?php echo esc_url( get_bio_image_url() ); ?>">
``` |
249,015 | <p>I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a "widget" method that will display the widget. Something like:</p>
<pre><code><?php
public function widget( $args, $instance ) {
echo $args['before_widget'];
?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php
echo $args['after_widget'];
}
?>
</code></pre>
<p>While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because <code>$args['after_widget'];</code> and <code>$args['before_widget'];</code> are not escaped...</p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 249020,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 4,
"selected": true,
"text": "<p>These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widge... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/249015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76144/"
] | I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a "widget" method that will display the widget. Something like:
```
<?php
public function widget( $args, $instance ) {
echo $args['before_widget'];
?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php
echo $args['after_widget'];
}
?>
```
While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because `$args['after_widget'];` and `$args['before_widget'];` are not escaped...
What am I doing wrong? | These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widgets code was designed and you can see in core Widget classes that no escaping is done on these.
Lessons to learn:
* WP core doesn't consistently adhere to its own coding standards (and getting there isn't considered worth targeted effort);
* passing around chunks of HTML is bad idea, in your own code pass *data* and render appropriately with proper escaping. |
249,017 | <p>I am trying to develop a method in my admin panel that will allow for the creation of a CSV file within the plugin directory
Here is my code: where $amount is the next increment of filename calculated beforehand (if 1.csv and 2.csv exist, then create 3.csv) this calculation works fine as I have tried echoing the filepath</p>
<pre><code> function createNewGallery($amount)
{
$files = $amount;
echo "CREATE NEW GALLERY";
$databaseURL = plugins_url( '/', __FILE__ );
$databaseURL .= $files + 1 . '.csv';
echo $databaseURL;
$headers = array('imageid', 'imgurl', 'IMGTEXT');
echo " $headers ";
$fp = fopen($databaseURL, 'w');
fwrite($fp, $headers);
fclose($fp);
}
</code></pre>
<p>The code above seems to execute but doesn't actually do anything. I want it to create the next iteration of the CSV in the directory specified and then push the headers to it, but looking at the live FTP nothing is happening </p>
| [
{
"answer_id": 249019,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>Writing to a plugin directory is not considered a proper practice:</p>\n\n<ol>\n<li>Plugin directories are overwrit... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/249017",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107110/"
] | I am trying to develop a method in my admin panel that will allow for the creation of a CSV file within the plugin directory
Here is my code: where $amount is the next increment of filename calculated beforehand (if 1.csv and 2.csv exist, then create 3.csv) this calculation works fine as I have tried echoing the filepath
```
function createNewGallery($amount)
{
$files = $amount;
echo "CREATE NEW GALLERY";
$databaseURL = plugins_url( '/', __FILE__ );
$databaseURL .= $files + 1 . '.csv';
echo $databaseURL;
$headers = array('imageid', 'imgurl', 'IMGTEXT');
echo " $headers ";
$fp = fopen($databaseURL, 'w');
fwrite($fp, $headers);
fclose($fp);
}
```
The code above seems to execute but doesn't actually do anything. I want it to create the next iteration of the CSV in the directory specified and then push the headers to it, but looking at the live FTP nothing is happening | If you plan to write to a pugin folder since you used `fopen`, `fwite`, `flose` you are using the wrong function:
```
File: wp-includes/link-template.php
3189: /**
3190: * Retrieves a URL within the plugins or mu-plugins directory.
3191: *
3192: * Defaults to the plugins directory URL if no arguments are supplied.
3193: *
3194: * @since 2.6.0
3195: *
3196: * @param string $path Optional. Extra path appended to the end of the URL, including
3197: * the relative directory if $plugin is supplied. Default empty.
3198: * @param string $plugin Optional. A full path to a file inside a plugin or mu-plugin.
3199: * The URL will be relative to its directory. Default empty.
3200: * Typically this is done by passing `__FILE__` as the argument.
3201: * @return string Plugins URL link with optional paths appended.
3202: */
3203: function plugins_url( $path = '', $plugin = '' ) {
3204:
```
You should probable use this function:
```
File: wp-includes/plugin.php
703: /**
704: * Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.
705: *
706: * @since 2.8.0
707: *
708: * @param string $file The filename of the plugin (__FILE__).
709: * @return string the filesystem path of the directory that contains the plugin.
710: */
711: function plugin_dir_path( $file ) {
712: return trailingslashit( dirname( $file ) );
713: }
```
Then you are on your own:
```
$plugin_dir = plugin_dir_path( __FILE__ );
$logfile = $plugin_dir . 'log.csv';
$fp = fopen($logfile, 'w');
fwrite($fp, $data);
fclose($fp);
```
>
> At the moment plugins in WordPress have all the rights WordPress have when writing to a file system, and these are the rights given from the web server process.
>
>
>
---
Your naming convention is not perfect: `$databaseURL` is probably bad chosen. This is not a URL. |
249,034 | <p>I'm using a theme that I've pulled from WordPress' repo (example: <a href="https://wordpress.org/themes/twentysixteen/" rel="nofollow noreferrer">Twenty Sixteen</a>), the default URL structure looks like so:</p>
<pre><code>http://example.com/wp-content/themes/twentysixteen/...
</code></pre>
<p>I want to hide any reference that this WordPress theme is coming from Twenty Sixteen and customize the directory to something else:</p>
<pre><code>http://example.com/wp-content/themes/my-site/...
</code></pre>
<p>While I can FTP to my website and rename the folder manually, I noticed that the theme does not receive any updates that are made on WordPress' repo.</p>
<p>I'd assume I would create a <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow noreferrer">child theme</a> referring to Twenty Sixteen in order to still receive the latest updates for the theme and still have a custom directory name. Is that the best route?</p>
| [
{
"answer_id": 249036,
"author": "Carl Willis",
"author_id": 69413,
"author_profile": "https://wordpress.stackexchange.com/users/69413",
"pm_score": 2,
"selected": true,
"text": "<p>changing the theme folder I guess it won't affect on updates but changing it's name do.</p>\n\n<p>So like ... | 2016/12/12 | [
"https://wordpress.stackexchange.com/questions/249034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | I'm using a theme that I've pulled from WordPress' repo (example: [Twenty Sixteen](https://wordpress.org/themes/twentysixteen/)), the default URL structure looks like so:
```
http://example.com/wp-content/themes/twentysixteen/...
```
I want to hide any reference that this WordPress theme is coming from Twenty Sixteen and customize the directory to something else:
```
http://example.com/wp-content/themes/my-site/...
```
While I can FTP to my website and rename the folder manually, I noticed that the theme does not receive any updates that are made on WordPress' repo.
I'd assume I would create a [child theme](https://codex.wordpress.org/Child_Themes) referring to Twenty Sixteen in order to still receive the latest updates for the theme and still have a custom directory name. Is that the best route? | changing the theme folder I guess it won't affect on updates but changing it's name do.
So like you said the best way that every professional company advice is to create a child-theme and modify everything you want on it. |
249,077 | <pre><code><?php
/*
* Plugin Name: Official Treehouse Badges Plugin
* Plugin URI: http://wptreehouse.com/wptreehouse-badges-plugin/
* Description: Provides both widgets and shortcodes to help you display your Treehouse profile badges on your website. The official Treehouse badges plugin.
* Version: 1.0
* Author: Editorial Staff
* Author URI: http://wp.zacgordon.com
* License: GPL2
*
*/
/*---------------------------------------*/
/* 1. ASSIGN GLOBAL VARIABLE */
/*---------------------------------------*/
/*---------------------------------------*/
/* 2. PLUGIN ADMIN MENU */
/*---------------------------------------*/
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
?>
</code></pre>
<p>I am just a beginner and have written a very simple basic plugin structure.</p>
<p>What's the mistake that's causing the "Treehouse Badges" menu name not to appear under the Settings menu in the admin section of WordPress.</p>
| [
{
"answer_id": 249078,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>The only issue was that the capability was specified incorrectly when using <code>add_options_page()</code>.... | 2016/12/13 | [
"https://wordpress.stackexchange.com/questions/249077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] | ```
<?php
/*
* Plugin Name: Official Treehouse Badges Plugin
* Plugin URI: http://wptreehouse.com/wptreehouse-badges-plugin/
* Description: Provides both widgets and shortcodes to help you display your Treehouse profile badges on your website. The official Treehouse badges plugin.
* Version: 1.0
* Author: Editorial Staff
* Author URI: http://wp.zacgordon.com
* License: GPL2
*
*/
/*---------------------------------------*/
/* 1. ASSIGN GLOBAL VARIABLE */
/*---------------------------------------*/
/*---------------------------------------*/
/* 2. PLUGIN ADMIN MENU */
/*---------------------------------------*/
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
?>
```
I am just a beginner and have written a very simple basic plugin structure.
What's the mistake that's causing the "Treehouse Badges" menu name not to appear under the Settings menu in the admin section of WordPress. | The only issue was that the capability was specified incorrectly when using `add_options_page()`. The capability should be `manage_options`. Note the underscore, no space:
```
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage_options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
``` |
249,082 | <p>I am trying to manually add a new plugin to WordPress site (I need to add a customized plugin).</p>
<p>I do it by:</p>
<ol>
<li><p>uploading it via Ftp server (with FTPS connection) to <code>/var/www/html/wp-content/plugins</code></p></li>
<li><p>Copy/paste to <code>/var/www/html/wp-content/plugins</code></p></li>
</ol>
<p>But, I am not able to see it on WordPress site under plugin section.</p>
<p>I am using:</p>
<ol>
<li>WordPress 4.7</li>
<li>Filezilla (FTP client) and VSFTPD (Ubuntu FTP server).</li>
<li>Ubuntu 16.10</li>
</ol>
<p>Any ideas as to what the issue is?</p>
| [
{
"answer_id": 249078,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>The only issue was that the capability was specified incorrectly when using <code>add_options_page()</code>.... | 2016/12/13 | [
"https://wordpress.stackexchange.com/questions/249082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107436/"
] | I am trying to manually add a new plugin to WordPress site (I need to add a customized plugin).
I do it by:
1. uploading it via Ftp server (with FTPS connection) to `/var/www/html/wp-content/plugins`
2. Copy/paste to `/var/www/html/wp-content/plugins`
But, I am not able to see it on WordPress site under plugin section.
I am using:
1. WordPress 4.7
2. Filezilla (FTP client) and VSFTPD (Ubuntu FTP server).
3. Ubuntu 16.10
Any ideas as to what the issue is? | The only issue was that the capability was specified incorrectly when using `add_options_page()`. The capability should be `manage_options`. Note the underscore, no space:
```
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage_options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
``` |
249,109 | <p>Is there a way to hide user profiles in the front end, while still allowing their information to be accessible in the backend?</p>
<p>Something similar to setting posts or pages to "draft" but for users would function perfectly. Is there a way to do this?</p>
| [
{
"answer_id": 249204,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>The database table for users holds the <code>user_status</code> as integer:</p>\n\n<pre><code> $users_singl... | 2016/12/13 | [
"https://wordpress.stackexchange.com/questions/249109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108864/"
] | Is there a way to hide user profiles in the front end, while still allowing their information to be accessible in the backend?
Something similar to setting posts or pages to "draft" but for users would function perfectly. Is there a way to do this? | The database table for users holds the `user_status` as integer:
```
$users_single_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
```
The `WP_Users` class at the moment doesn't have anything that would alter the state property, nor even hold that property.
[](https://i.stack.imgur.com/ta8H2.png)
There is one function inside `wp-admin/includes/ms.php` that may show you the path how to go.
```
update_user_status( $user_id, 'spam', '1' );
```
but loads only for multisite:
```
/wp-admin/includes/admin.php:
82 if ( is_multisite() ) {
83 require_once(ABSPATH . 'wp-admin/includes/ms-admin-filters.php');
84: require_once(ABSPATH . 'wp-admin/includes/ms.php');
85 require_once(ABSPATH . 'wp-admin/includes/ms-deprecated.php');
86 }
```
It looks like this:
```
function update_user_status( $id, $pref, $value, $deprecated = null ) {
global $wpdb;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.0.2' );
$wpdb->update( $wpdb->users, array( sanitize_key( $pref ) => $value ), array( 'ID' => $id ) );
$user = new WP_User( $id );
clean_user_cache( $user );
if ( $pref == 'spam' ) {
if ( $value == 1 ) {
/**
* Fires after the user is marked as a SPAM user.
*
* @since 3.0.0
*
* @param int $id ID of the user marked as SPAM.
*/
do_action( 'make_spam_user', $id );
} else {
/**
* Fires after the user is marked as a HAM user. Opposite of SPAM.
*
* @since 3.0.0
*
* @param int $id ID of the user marked as HAM.
*/
do_action( 'make_ham_user', $id );
}
}
return $value;
}
```
You could use something similar and create **the action hook** `make_draft_user`, probable in your function `_20161214_update_user_status( $user_id, 'draft', '1' );`
Inside your very own `make_draft_user` hook you could define what to do.
>
> So WordPress out of the box doesn't provide draft users. Maybe it will one day with the clear use case scenario. Maybe the status will be a string, and not the int (This is the case for posts).
>
>
> |
249,115 | <p>I want to show author avatar in post info. So I use</p>
<pre><code><?php echo get_avatar( get_the_author_meta( 'ID' ) , 80); ?>
</code></pre>
<p>But how can I check if user has avatar? </p>
| [
{
"answer_id": 249117,
"author": "Oreo",
"author_id": 108862,
"author_profile": "https://wordpress.stackexchange.com/users/108862",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_avatar()</code> returns An img element for the user's avatar or false on failure. The function does ... | 2016/12/13 | [
"https://wordpress.stackexchange.com/questions/249115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103556/"
] | I want to show author avatar in post info. So I use
```
<?php echo get_avatar( get_the_author_meta( 'ID' ) , 80); ?>
```
But how can I check if user has avatar? | `get_avatar()` returns An img element for the user's avatar or false on failure. The function does not output anything; you have to echo the return value.
so you can try something like that
```
if( get_avatar( get_the_author_meta( 'ID' ) ) == 0) {
// no img code
} else {
echo get_avatar( get_the_author_meta( 'ID' ) , 80 );
}
``` |
249,190 | <p>I have put this code on author.php page</p>
<pre><code> <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
//gets the number of comment(s) on a post
$comments_number = get_comments_number();
//adds all the comment counts up
$numbercomment += $comments_number;
?>
<?php endwhile; ?>
<span>A total of <?php echo $numbercomment; ?> comments have been made on this author posts.</span>
</code></pre>
<p>Currently i am using a loop to find number of a comments on a post and total it with all the other comment count on other posts. The consists of only the author's post so in that way i can find the number of comments people have made on that specific author's posts.
Is there a simpler way of doing it.</p>
<p>EDIT:<br>
I want to count the total number of comments people have made on all of that author's posts.
Put the above code up in author.php file and you will get what i mean..</p>
| [
{
"answer_id": 249196,
"author": "Pim",
"author_id": 50432,
"author_profile": "https://wordpress.stackexchange.com/users/50432",
"pm_score": 3,
"selected": true,
"text": "<p>You could use <code>get_comments()</code>, this way you don't have to loop through posts.</p>\n\n<pre><code><?p... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75425/"
] | I have put this code on author.php page
```
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
//gets the number of comment(s) on a post
$comments_number = get_comments_number();
//adds all the comment counts up
$numbercomment += $comments_number;
?>
<?php endwhile; ?>
<span>A total of <?php echo $numbercomment; ?> comments have been made on this author posts.</span>
```
Currently i am using a loop to find number of a comments on a post and total it with all the other comment count on other posts. The consists of only the author's post so in that way i can find the number of comments people have made on that specific author's posts.
Is there a simpler way of doing it.
EDIT:
I want to count the total number of comments people have made on all of that author's posts.
Put the above code up in author.php file and you will get what i mean.. | You could use `get_comments()`, this way you don't have to loop through posts.
```
<?php
$args = array(
'post_author' => '' // fill in post author ID
);
$author_comments = get_comments($args);
echo count($author_comments);
?>
``` |
249,202 | <p>Is it possible to order a tag page by the 'most commonly used' tag? </p>
<p>For example:</p>
<p>Say I have three tags: Apple, Orange, Banana, and 100 posts. </p>
<p>90 of those posts are tagged Apple, 50 are tagged Orange, and 20 are tagged Banana. (Some are tagged with more than 1 tag.) </p>
<p>So I want to order the posts listed on the tags page by Apple Tags first.</p>
<p>Right now, I am ordering by last modified using the following query, but would like to order by the tag that is used the most across all posts.</p>
<pre><code> $args = array(
'posts_per_page' => 10, // Get 10 posts
'paged' => $paged,
'post_type' => 'post',
'tag' => $tag->slug,
'orderby' => 'modified'
);
</code></pre>
| [
{
"answer_id": 249338,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>I'm afraid <code>orderby</code> taxonomy terms post count is not possible by <code>WP_Query</code>. <a href... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249202",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44848/"
] | Is it possible to order a tag page by the 'most commonly used' tag?
For example:
Say I have three tags: Apple, Orange, Banana, and 100 posts.
90 of those posts are tagged Apple, 50 are tagged Orange, and 20 are tagged Banana. (Some are tagged with more than 1 tag.)
So I want to order the posts listed on the tags page by Apple Tags first.
Right now, I am ordering by last modified using the following query, but would like to order by the tag that is used the most across all posts.
```
$args = array(
'posts_per_page' => 10, // Get 10 posts
'paged' => $paged,
'post_type' => 'post',
'tag' => $tag->slug,
'orderby' => 'modified'
);
``` | I'm afraid `orderby` taxonomy terms post count is not possible by `WP_Query`. [See this answer](https://wordpress.stackexchange.com/questions/14306/using-wp-query-is-it-possible-to-orderby-taxonomy/14309#14309). So here I've written a SQL based function for you. It'll order your posts based on terms post count.
```
function the_dramatist_order_posts_by_tag_count( $args = '' ) {
global $wpdb;
$param = empty($args) ? 'post_tag' : $args;
$sql = $wpdb->prepare("SELECT posts.*, terms.name AS tag, count
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->term_relationships} AS t_rel
ON (t_rel.object_id = posts.ID)
LEFT JOIN {$wpdb->term_taxonomy} AS t_tax
ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)
LEFT JOIN {$wpdb->terms} AS terms
ON (terms.term_id = t_tax.term_id)
WHERE taxonomy LIKE '%s'
ORDER BY t_tax.count DESC, terms.name",
array( $param )
);
return $wpdb->get_results($sql);
}
```
It'll return you all the data from you posts table with `post_tag` term name and this terms post count. But it has a simple limitation and that is if you have one tag in multiple posts then the post will appear multiple time for each `post_tag` term it is attached to. You can use `GROUP BY posts.ID` to remove the duplicate posts, but it'll not give you all the terms and terms count. So with `GROUP BY posts.ID` the function will be like below-
```
function the_dramatist_order_posts_by_tag_count( $args = '' ) {
global $wpdb;
$param = empty($args) ? 'post_tag' : $args;
$sql = $wpdb->prepare("SELECT posts.*, terms.name AS tag, count
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->term_relationships} AS t_rel
ON (t_rel.object_id = posts.ID)
LEFT JOIN {$wpdb->term_taxonomy} AS t_tax
ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)
LEFT JOIN {$wpdb->terms} AS terms
ON (terms.term_id = t_tax.term_id)
WHERE taxonomy LIKE '%s'
GROUP BY posts.ID
ORDER BY t_tax.count DESC, terms.name",
array( $param )
);
return $wpdb->get_results($sql);
}
```
Use which suits your need better.
This function works on `post_tag` taxonomy by default. If you want to use it with other taxonomy just pass it as parameter like `the_dramatist_order_posts_by_tag_count( 'category' )`
Better you do a `print_r` on this function before using it in production to understand the data structure.
Hope that helps. |
249,214 | <p>I have a piece of code displaying a list of sites in my multisite, and I want to exclude the archived ones:</p>
<pre><code>$mySites = ( wp_get_sites( $args ) );
foreach ( $mySites as $blog ) {
if ( ! ( is_archived($blog) ) ) {
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
</code></pre>
<p>Before updating to 4.7, this was working correctly. Now, it doesn't exclude archived sites anymore, it prints out a complete list. </p>
<p>Has the function <code>is_archived()</code> changed? Or what can the problem be?</p>
| [
{
"answer_id": 249222,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 3,
"selected": true,
"text": "<p>Can you try out the following code somewhere and post the output?</p>\n\n<pre><code>$mySites = wp_get_sites($args... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249214",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78708/"
] | I have a piece of code displaying a list of sites in my multisite, and I want to exclude the archived ones:
```
$mySites = ( wp_get_sites( $args ) );
foreach ( $mySites as $blog ) {
if ( ! ( is_archived($blog) ) ) {
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
```
Before updating to 4.7, this was working correctly. Now, it doesn't exclude archived sites anymore, it prints out a complete list.
Has the function `is_archived()` changed? Or what can the problem be? | Can you try out the following code somewhere and post the output?
```
$mySites = wp_get_sites($args);
foreach ($mySites as $blog){
print_r(get_blog_status($blog['blog_id'], 'archived'));
}
```
If this works, I suspect the code behind `is_archived()` used to understand blog-objects, but the [function is supposed to recieve only the blog ID](https://developer.wordpress.org/reference/functions/is_archived/), not the whole object.
Your code should be the following:
```
$mySites = wp_get_sites($args);
foreach ($mySites as $blog){
if (!is_archived($blog['blog_id'])){
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
``` |
249,218 | <p>WordPress has several APIs build in:</p>
<ul>
<li><a href="https://codex.wordpress.org/XML-RPC_WordPress_API" rel="noreferrer">XML-RPC</a></li>
<li><a href="http://v2.wp-api.org/" rel="noreferrer">REST API</a></li>
</ul>
<p>by default they don't return custom post types or protected meta keys.</p>
<p>I want to access the protected meta fields of a plugin. I tried to follow the examples given <a href="https://journal.rmccue.io/351/the-complex-state-of-meta-in-the-wordpress-rest-api/" rel="noreferrer">here</a> and <a href="https://developer.wordpress.org/rest-api/adding-rest-api-support-for-custom-content-types/" rel="noreferrer">here</a>.</p>
<p>I did manage that the wp-json API would return custom post types by adding this code:</p>
<pre><code>/**
* Add REST API support to an already registered post type.
*/
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
// be sure to set this to the name of your post type!
$post_type_name = 'tribe_venue';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
$post_type_name2 = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name2 ] ) ) {
$wp_post_types[$post_type_name2]->show_in_rest = true;
$wp_post_types[$post_type_name2]->rest_base = $post_type_name2;
$wp_post_types[$post_type_name2]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
</code></pre>
<p>But I was not able to include protected meta keys in the response.</p>
<p>I tried the following code:</p>
<pre><code>add_filter( 'is_protected_meta', function ( $protected, $key, $type ) {
if ( $type === 'tribe_venue' && $key === '_VenueVenue' ) {
return true;
}
return $protected;
}, 10, 3 );
add_filter( 'rae_include_protected_meta', '__return_true' );
</code></pre>
<p>and the following code:</p>
<pre><code>function custom_rest_api_allowed_public_metadata($allowed_meta_keys){
$allowed_meta_keys[] = '_VenueVenue';
$allowed_meta_keys[] = '_VenueAddress';
$allowed_meta_keys[] = '_VenueCity';
return $allowed_meta_keys;
}
add_filter( 'rest_api_allowed_public_metadata', 'custom_rest_api_allowed_public_metadata' );
</code></pre>
<p>but neither works.</p>
<p>Does anybody know what is needed so make such protected fields accessible through any of the APIs? Is there a working example anywhere? </p>
| [
{
"answer_id": 263457,
"author": "J.C. Hiatt",
"author_id": 117545,
"author_profile": "https://wordpress.stackexchange.com/users/117545",
"pm_score": 0,
"selected": false,
"text": "<p>With the REST API, there's a <code>rest_query_vars</code> filter you can use:</p>\n\n<pre><code>function... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249218",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80953/"
] | WordPress has several APIs build in:
* [XML-RPC](https://codex.wordpress.org/XML-RPC_WordPress_API)
* [REST API](http://v2.wp-api.org/)
by default they don't return custom post types or protected meta keys.
I want to access the protected meta fields of a plugin. I tried to follow the examples given [here](https://journal.rmccue.io/351/the-complex-state-of-meta-in-the-wordpress-rest-api/) and [here](https://developer.wordpress.org/rest-api/adding-rest-api-support-for-custom-content-types/).
I did manage that the wp-json API would return custom post types by adding this code:
```
/**
* Add REST API support to an already registered post type.
*/
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
// be sure to set this to the name of your post type!
$post_type_name = 'tribe_venue';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
$post_type_name2 = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name2 ] ) ) {
$wp_post_types[$post_type_name2]->show_in_rest = true;
$wp_post_types[$post_type_name2]->rest_base = $post_type_name2;
$wp_post_types[$post_type_name2]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
```
But I was not able to include protected meta keys in the response.
I tried the following code:
```
add_filter( 'is_protected_meta', function ( $protected, $key, $type ) {
if ( $type === 'tribe_venue' && $key === '_VenueVenue' ) {
return true;
}
return $protected;
}, 10, 3 );
add_filter( 'rae_include_protected_meta', '__return_true' );
```
and the following code:
```
function custom_rest_api_allowed_public_metadata($allowed_meta_keys){
$allowed_meta_keys[] = '_VenueVenue';
$allowed_meta_keys[] = '_VenueAddress';
$allowed_meta_keys[] = '_VenueCity';
return $allowed_meta_keys;
}
add_filter( 'rest_api_allowed_public_metadata', 'custom_rest_api_allowed_public_metadata' );
```
but neither works.
Does anybody know what is needed so make such protected fields accessible through any of the APIs? Is there a working example anywhere? | To me, the simplest solution would be creating additional field in JSON response and populating it with selected post meta:
```
function create_api_posts_meta_field() {
// "tribe_venue" is your post type name,
// "protected-fields" is a name for new JSON field
register_rest_field( 'tribe_venue', 'protected-fields', [
'get_callback' => 'get_post_meta_for_api',
'schema' => null,
] );
}
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
/**
* Callback function to populate our JSON field
*/
function get_post_meta_for_api( $object ) {
$meta = get_post_meta( $object['id'] );
return [
'venue' => $meta['_VenueVenue'] ?: '',
'address' => $meta['_VenueAddress'] ?: '',
'city' => $meta['_VenueCity'] ?: '',
];
}
```
You should be able to see your meta data both in
`/wp-json/wp/v2/tribe_venue/` and
`/wp-json/wp/v2/tribe_venue/{POST_ID}` |
249,221 | <p>I was creating a custom plugin which was to send certain emails based on the content/category of a post, but whilst trying to do that, I ran into some problems just getting a basic email sent out. Am I hooking on to the wrong function here? When I publish a post, nothing happens.</p>
<pre><code><?php
/**
* Plugin Name: Conditional Emailing
* Description: Sends emails based on categories.
* Version: 1.0
* Author: Ceds
*/
add_action( 'new_to_publish', 'conditional_email', 10, 0);
function conditional_email() {
wp_mail('my@email.com','test','test');
}
?>
</code></pre>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre>... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103117/"
] | I was creating a custom plugin which was to send certain emails based on the content/category of a post, but whilst trying to do that, I ran into some problems just getting a basic email sent out. Am I hooking on to the wrong function here? When I publish a post, nothing happens.
```
<?php
/**
* Plugin Name: Conditional Emailing
* Description: Sends emails based on categories.
* Version: 1.0
* Author: Ceds
*/
add_action( 'new_to_publish', 'conditional_email', 10, 0);
function conditional_email() {
wp_mail('my@email.com','test','test');
}
?>
```
What am I doing wrong here? | You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('my@email.com','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after ! |
249,233 | <p>I need to organize the pages on my website so that they appear with the proper hierarchy. The problem is that the category-derived page is appearing outside my hierarchy. This is the current hierarchy if you are on my site today:</p>
<pre><code>Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/category/policy
</code></pre>
<p>I need the policy category page to appear under Internal, which is accessible only by my registered users, such as:</p>
<pre><code>Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/internal/policy
</code></pre>
<p>I have other (External/Public) category pages that need to be handed differently. Any ideas as to how I can make this happen would be much appreciated.</p>
| [
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre>... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51855/"
] | I need to organize the pages on my website so that they appear with the proper hierarchy. The problem is that the category-derived page is appearing outside my hierarchy. This is the current hierarchy if you are on my site today:
```
Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/category/policy
```
I need the policy category page to appear under Internal, which is accessible only by my registered users, such as:
```
Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/internal/policy
```
I have other (External/Public) category pages that need to be handed differently. Any ideas as to how I can make this happen would be much appreciated. | You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('my@email.com','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after ! |
249,237 | <p>I'm using [feed to post RSS Aggregator] and get posts from 44 sites. main page loading is too slow. I checked GTmetrix and it seems good but I don't know how can I improve my website loading. <a href="http://akhbartop.ir/" rel="nofollow noreferrer">http://akhbartop.ir/</a></p>
| [
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre>... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249237",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101761/"
] | I'm using [feed to post RSS Aggregator] and get posts from 44 sites. main page loading is too slow. I checked GTmetrix and it seems good but I don't know how can I improve my website loading. <http://akhbartop.ir/> | You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('my@email.com','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after ! |
249,248 | <p>So I've got to edit my 404 page. Since my client's website has 5 languages, I'd like to let him edit and translate the 404 page by himself, with normal WordPress editor. Also, we're currently using Polylang as the localization plugin.</p>
<p>Is there a way to have the theme's <code>404.php</code> as a regular page?</p>
<p>I've tried to create a page and then assign it to the 404 template via template name, but it doesn't work, because it seems that <code>$post</code> is not available inside the template, so I cannot write contents.</p>
| [
{
"answer_id": 249260,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": false,
"text": "<p>Found a way.</p>\n\n<ul>\n<li><p>Create a regular page for 404 content, say 'Page not found';</p></li>... | 2016/12/14 | [
"https://wordpress.stackexchange.com/questions/249248",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | So I've got to edit my 404 page. Since my client's website has 5 languages, I'd like to let him edit and translate the 404 page by himself, with normal WordPress editor. Also, we're currently using Polylang as the localization plugin.
Is there a way to have the theme's `404.php` as a regular page?
I've tried to create a page and then assign it to the 404 template via template name, but it doesn't work, because it seems that `$post` is not available inside the template, so I cannot write contents. | Found a way.
* Create a regular page for 404 content, say 'Page not found';
* In your 404.php file, get that page data and then write down your content or whatever...
For example:
```
$page = get_page_by_title("Page not found");
if($page) echo apply_filters('the_content',$page->post_content);
```
Obviously, you can do a lot more... |
249,309 | <p>I logged into my wp-dashboard after a hack to find that there is a 'ghost' administrator of my site... the only problem is, I can't just list the user table and delete it. I don't know why, but here's all I get when I click on the Admin tab, or the subscribers tab for that matter:</p>
<p><a href="https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0</a></p>
<p>It only lists me!</p>
<p>So, I know that the meta value for an admin is in the wp-usermeta and then wp-capabilities table... and is: meta_value='a:1:{s:13:"administrator";b:1;}</p>
<p>However, I'm really new to phpmyadmin, and I have no idea how to search for this. It doesn't even look like I have this table either:</p>
<p><a href="https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0</a></p>
<p>No idea where to go from here :-(</p>
<p>Your help would be much appreciated. Thanks for your time!</p>
| [
{
"answer_id": 249325,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 1,
"selected": false,
"text": "<p>Navigate to the wp_users table on your php myadmin and see if you are the only one on the table. If so c... | 2016/12/15 | [
"https://wordpress.stackexchange.com/questions/249309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108987/"
] | I logged into my wp-dashboard after a hack to find that there is a 'ghost' administrator of my site... the only problem is, I can't just list the user table and delete it. I don't know why, but here's all I get when I click on the Admin tab, or the subscribers tab for that matter:
<https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0>
It only lists me!
So, I know that the meta value for an admin is in the wp-usermeta and then wp-capabilities table... and is: meta\_value='a:1:{s:13:"administrator";b:1;}
However, I'm really new to phpmyadmin, and I have no idea how to search for this. It doesn't even look like I have this table either:
<https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0>
No idea where to go from here :-(
Your help would be much appreciated. Thanks for your time! | We can generate the SQL with:
```
$query = new WP_User_Query(
[
'role' => 'Administrator',
'count_total' => false,
]
);
echo $query->request;
```
that outputs:
```
SELECT wp_users.*
FROM wp_users
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
WHERE 1=1
AND ( ( ( wp_usermeta.meta_key = 'wp_capabilities'
AND wp_usermeta.meta_value LIKE '%\"Administrator\"%' ) ) )
ORDER BY user_login ASC
```
You might have a different table prefix, than showed here.
Note that deleting the hidden administrator user, will most likely not fix the problem, as there might still be other backdoor(s). Recovering hacked sites is in general off topic here, but you could try to contact your hosting provider or security experts, regarding available backups, security reviews, etc. |
249,330 | <p>I want to run a WordPress code Snippet that can show total posts by author.
something like this:</p>
<p>author1: 37 posts
author2: 12 posts
author3: 43 posts</p>
<p>is possible this?.
Thank you</p>
| [
{
"answer_id": 249333,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 1,
"selected": false,
"text": "<p>First of all you need to get all users calling <code>get_users()</code> function. Then you can use <code>cou... | 2016/12/15 | [
"https://wordpress.stackexchange.com/questions/249330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108998/"
] | I want to run a WordPress code Snippet that can show total posts by author.
something like this:
author1: 37 posts
author2: 12 posts
author3: 43 posts
is possible this?.
Thank you | First of all you need to get all users calling `get_users()` function. Then you can use `count_user_posts()` to display post count for a user.
Try below code.
```
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';
}
?>
```
**Update : You can easily use `wp_list_authors()` function also.**
```
<?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>
``` |
249,429 | <p>I created a plugin to override a theme's function. As I learn that function in plugin loads first but I got an error </p>
<blockquote>
<p>Fatal error: Cannot redeclare wooc_extra_register_fields() (previously
declared in ****/themes/****/functions.php:247) in
***/plugins/custom-plugin/custom-plugin.php on line 89</p>
</blockquote>
<p>Not sure what I am doing wrong.
Also put theme's functions need to be override in if !function exist.
So what is the right way to override a theme function wrap in !function exist using a plugin??</p>
| [
{
"answer_id": 249333,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 1,
"selected": false,
"text": "<p>First of all you need to get all users calling <code>get_users()</code> function. Then you can use <code>cou... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52602/"
] | I created a plugin to override a theme's function. As I learn that function in plugin loads first but I got an error
>
> Fatal error: Cannot redeclare wooc\_extra\_register\_fields() (previously
> declared in \*\*\*\*/themes/\*\*\*\*/functions.php:247) in
> \*\*\*/plugins/custom-plugin/custom-plugin.php on line 89
>
>
>
Not sure what I am doing wrong.
Also put theme's functions need to be override in if !function exist.
So what is the right way to override a theme function wrap in !function exist using a plugin?? | First of all you need to get all users calling `get_users()` function. Then you can use `count_user_posts()` to display post count for a user.
Try below code.
```
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';
}
?>
```
**Update : You can easily use `wp_list_authors()` function also.**
```
<?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>
``` |
249,437 | <p>I have created a new role .Now I want to remove <strong>post</strong> ,<strong>media</strong>, <strong>setting</strong> capability for that role.
How can I achieve this?</p>
| [
{
"answer_id": 249440,
"author": "ehabdevel",
"author_id": 109068,
"author_profile": "https://wordpress.stackexchange.com/users/109068",
"pm_score": 1,
"selected": false,
"text": "<p>Remove a top level admin menu:</p>\n\n<pre><code> function custom_menu_page_removing() {\n remove_m... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249437",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109067/"
] | I have created a new role .Now I want to remove **post** ,**media**, **setting** capability for that role.
How can I achieve this? | Remove a top level admin menu:
```
function custom_menu_page_removing() {
remove_menu_page( $menu_slug );
}
add_action( 'admin_menu', 'custom_menu_page_removing' );
```
To remove only certain menu items include only those you want to hide within the function.
To remove menus for only certain users you may want to utilize current\_user\_can().
You can take a look at <https://codex.wordpress.org/Function_Reference/remove_menu_page> |
249,438 | <p>I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". for this issue I fixed it by using below js code:</p>
<pre><code>history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
</code></pre>
<p>The browser back button issue fixed but after adding the above js code I got new issue i.e. browser back button totally getting disabled, what if user wants to use browser back button to navigate through the site web pages? </p>
<p><strong>IS there any hook that I can write in theme functions.php file?</strong> so that I can fix this issue if user clicks on browser back button after logout? can anyone please tell me how to fix it?</p>
<p>I tried the one below but din't work either:</p>
<pre><code><script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
</code></pre>
<p>what's wrong plz can anyone tell me! </p>
| [
{
"answer_id": 249443,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>When a user <a href=\"https://codex.wordpress.org/Function_Reference/wp_logout\" rel=\"nofollow noreferrer\">log... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] | I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". for this issue I fixed it by using below js code:
```
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
```
The browser back button issue fixed but after adding the above js code I got new issue i.e. browser back button totally getting disabled, what if user wants to use browser back button to navigate through the site web pages?
**IS there any hook that I can write in theme functions.php file?** so that I can fix this issue if user clicks on browser back button after logout? can anyone please tell me how to fix it?
I tried the one below but din't work either:
```
<script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
```
what's wrong plz can anyone tell me! | When a user [logs out](https://codex.wordpress.org/Function_Reference/wp_logout) the current user session is destroyed and no new pages can be loaded for which a user must be logged in. However, when you hit the 'back' button on your browser, it typically retrieves the page from the local cache. There is no contact with the server to see if the current session is still valid.
So, what you need to do is detect whether the backspace button has been hit and in that case check the validity of the session. This means there must be a piece of javacript included in the page, because this action needs to take place at the user side. I'm not a security expert, but the common way to detect the backspace goes like this:
```
window.onhashchange = function() {
.. your action ..
}
```
There are [some snags](https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser) to this method. Now, your action must be to call back to the server. That question [has been answered before](https://wordpress.stackexchange.com/questions/69814/check-if-user-is-logged-in-using-jquery) here on WPSE. |
249,456 | <p>I'm interested in using an old version of a plugin for a core feature on the site (it's not ideal but a compromise after months of effort) because the new version has incompatibilities. However I'm worried that someone - including myself - will mindlessly update the plugin in the future.</p>
<p>Is there any way to prevent a WordPress plugin from searching for updates?</p>
| [
{
"answer_id": 249482,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p>It is quite simple. All you have to do is add some code in a Custom Functions plugin.</p>\n\n<p>Lets say... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249456",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96983/"
] | I'm interested in using an old version of a plugin for a core feature on the site (it's not ideal but a compromise after months of effort) because the new version has incompatibilities. However I'm worried that someone - including myself - will mindlessly update the plugin in the future.
Is there any way to prevent a WordPress plugin from searching for updates? | It is quite simple. All you have to do is add some code in a Custom Functions plugin.
Lets say you want to block the "Hello Dolly" plugin (comes prepacked with WordPress) from updating. In your "My Functions Plugin", `mycustomfunctions.php` (you can use any name really) you place the following:
```
/* Disable a plugin from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
That is all.
Now in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this:
```
/* Disable some plugins from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
unset( $value->response[ 'akismet/akismet.php' ] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
**Things to notice**:
* It is always best practice to **keep everything updated to the latest version** (for obvious reasons and mainly for vulnerability issues).
* We use `akismet/akismet.php` because `akismet.php` is within the plugin folder `akismet`
* In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: [Creating a custom functions plugin for end users](http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users).
* Also, please have a look at this post about: [Where to put my code: plugin or functions.php](https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php). |
249,472 | <p>I have written a code for inserting wordpress user if I try to add new user I am getting 3 warning errors saying like below: </p>
<p>"Warning: mysql_real_escape_string() expects parameter 1 to be string, object given in /home/intecom/public_html/app/wp-includes/wp-db.php on line 1129
" , </p>
<p>"Warning: Illegal offset type in isset or empty in /home/intecom/public_html/app/wp-includes/cache.php on line 725" </p>
<p>and </p>
<p>"Warning: array_key_exists(): The first argument should be either a string or an integer in /home/intecom/public_html/app/wp-includes/cache.php on line 725". </p>
<p>my code is below:</p>
<pre><code> $first_name = 'my_firstname_value';
$last_name = 'my_lastname_value';
$trainer_email = 'trainer@example.com';
$course_registered = Array
(
[0] => 2410
);
$pro_icon_status = '1';
$this->institute_icon[0] = '1';
$this->institute_name[0] = 'my_institute_name';
$user_data = array(
'user_login' => $first_name,
'user_pass' => '',
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'course_registered',$course_registered );
update_user_meta( $user_id, 'inistitute_name',$this->institute_name[0] );
update_user_meta( $user_id, 'inistitute_icon',$this->institute_icon[0] );
update_user_meta( $user_id, 'trainer_icon',$pro_icon_status );
wp_set_password($random_password, $user_id);
</code></pre>
<p>My input is only either string (or) array but why it is saying that "Iam passing object" I don't know what is happening. It is driving me nuts. can any one please tell me what was my mistake? Thanks in advance.</p>
<p>Update: The problem is not with 'wp_insert_user' or 'update_user_meta', actual problem is with the data that I was giving i.e. Am giving the same user_login name which is already there in the database, I am getting the WP_Error Object as below:</p>
<pre><code> WP_Error Object
(
[errors] => Array
(
[existing_user_login] => Array
(
[0] => Sorry, that username already exists!
)
)
[error_data] => Array
(
)
)
</code></pre>
<p>Now can u plz tell me how to show that error to user on the front end?</p>
| [
{
"answer_id": 249482,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p>It is quite simple. All you have to do is add some code in a Custom Functions plugin.</p>\n\n<p>Lets say... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] | I have written a code for inserting wordpress user if I try to add new user I am getting 3 warning errors saying like below:
"Warning: mysql\_real\_escape\_string() expects parameter 1 to be string, object given in /home/intecom/public\_html/app/wp-includes/wp-db.php on line 1129
" ,
"Warning: Illegal offset type in isset or empty in /home/intecom/public\_html/app/wp-includes/cache.php on line 725"
and
"Warning: array\_key\_exists(): The first argument should be either a string or an integer in /home/intecom/public\_html/app/wp-includes/cache.php on line 725".
my code is below:
```
$first_name = 'my_firstname_value';
$last_name = 'my_lastname_value';
$trainer_email = 'trainer@example.com';
$course_registered = Array
(
[0] => 2410
);
$pro_icon_status = '1';
$this->institute_icon[0] = '1';
$this->institute_name[0] = 'my_institute_name';
$user_data = array(
'user_login' => $first_name,
'user_pass' => '',
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'course_registered',$course_registered );
update_user_meta( $user_id, 'inistitute_name',$this->institute_name[0] );
update_user_meta( $user_id, 'inistitute_icon',$this->institute_icon[0] );
update_user_meta( $user_id, 'trainer_icon',$pro_icon_status );
wp_set_password($random_password, $user_id);
```
My input is only either string (or) array but why it is saying that "Iam passing object" I don't know what is happening. It is driving me nuts. can any one please tell me what was my mistake? Thanks in advance.
Update: The problem is not with 'wp\_insert\_user' or 'update\_user\_meta', actual problem is with the data that I was giving i.e. Am giving the same user\_login name which is already there in the database, I am getting the WP\_Error Object as below:
```
WP_Error Object
(
[errors] => Array
(
[existing_user_login] => Array
(
[0] => Sorry, that username already exists!
)
)
[error_data] => Array
(
)
)
```
Now can u plz tell me how to show that error to user on the front end? | It is quite simple. All you have to do is add some code in a Custom Functions plugin.
Lets say you want to block the "Hello Dolly" plugin (comes prepacked with WordPress) from updating. In your "My Functions Plugin", `mycustomfunctions.php` (you can use any name really) you place the following:
```
/* Disable a plugin from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
That is all.
Now in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this:
```
/* Disable some plugins from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
unset( $value->response[ 'akismet/akismet.php' ] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
**Things to notice**:
* It is always best practice to **keep everything updated to the latest version** (for obvious reasons and mainly for vulnerability issues).
* We use `akismet/akismet.php` because `akismet.php` is within the plugin folder `akismet`
* In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: [Creating a custom functions plugin for end users](http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users).
* Also, please have a look at this post about: [Where to put my code: plugin or functions.php](https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php). |
249,483 | <p>I have seen many articles mentioning that a <code>/%postname%/</code> permalink is the best for SEO. But what about a <code>/%post_id%/%postname%</code> structure, such as <code>myblog.com/123/the-slug-of-my-blog</code> ?</p>
<ul>
<li>It doesn't seem to affect search engine rankings (Stack Exchange and many others use this structure)</li>
<li>You make each permalink unique, even with the same slug (preventing the dreaded appending of "-2" in the slug)</li>
<li>You can even use <code>myblog.com/123</code> as a short-url, or an easy to say url in a podcast, etc (maybe you need a bit of code customization to achieve this)</li>
</ul>
<p>Is there any known performance issue about this permalink structure?</p>
| [
{
"answer_id": 249500,
"author": "Game Unity",
"author_id": 83769,
"author_profile": "https://wordpress.stackexchange.com/users/83769",
"pm_score": 0,
"selected": false,
"text": "<p>There shouldn't be any diffrents. I recommend you to use the ID version and you coold even make it prettie... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101799/"
] | I have seen many articles mentioning that a `/%postname%/` permalink is the best for SEO. But what about a `/%post_id%/%postname%` structure, such as `myblog.com/123/the-slug-of-my-blog` ?
* It doesn't seem to affect search engine rankings (Stack Exchange and many others use this structure)
* You make each permalink unique, even with the same slug (preventing the dreaded appending of "-2" in the slug)
* You can even use `myblog.com/123` as a short-url, or an easy to say url in a podcast, etc (maybe you need a bit of code customization to achieve this)
Is there any known performance issue about this permalink structure? | Note: we're talking here about the difference between permalinks `/%ID%/%name%/` and `%/name/%`. It would be a whole different story if we were to compare `/%ID%/%name%/` and `%/ID/%`.
Now, there are two use cases that affect performance:
**One. You have a permalink and WP needs to resolve it in order to serve the page requested.**
This means setting up the [WP class](https://developer.wordpress.org/reference/classes/wp/). The main function is at the bottom of the code. After init this involves calling [`parse_request`](https://developer.wordpress.org/reference/classes/wp/parse_request/). This checks whether rewrite rules exist for this particular page and checks query variables for validity. In this case we'd like to know whether processing `example.com/123/slug` takes more time than `example.com/slug`. For that to matter you would have to assume that the PHP string function that needs to handle a few bytes more has a significant impact on performance.
Once the requested url has been chopped into workable chunks, the action moves to [`parse_query`](https://developer.wordpress.org/reference/classes/wp_query/parse_query/), which in this case will be passed a query object either containing `name` or both `name` and `ID` (confusingly in the query object the ID is called `p`). A lot of handling is done, but nothing extra for including the ID in the query.
Next follow two hooks in (`pre_get_posts` and `posts_selection`) that are plugin territory, so impact on performance is unknown.
Now comes the main issue: will it take more time to query the database with one variable or with two? Both `ID` and `name` are stored in the `wp_posts` table in the database. So, there is no difference in the size of the table that will be queried. Also, both are unique, because when a post is stored this is checked (OP's assumption that including ID in the url will get rid of the `-2` in posts is wrong, unless you hack the saving procedure). As a result, it doesn't really matter whether you have to query all database rows for the unique `ID` or the unique `name`. The only difference in performance when providing both is that after the row with the `ID` has been found it will check if the `name` matches. That really is negligible.
**Two. You need to generate a permalink on a page.**
This is done by the [`get_permalink`](https://developer.wordpress.org/reference/functions/get_permalink/) function. For standard post types the procedure only adds some lengthy calculations if you are using `%category%`. For `ID` and `name` it is just a matter of search and replace in this line of code:
```
$permalink = home_url( str_replace( $rewritecode, $rewritereplace, $permalink ) );
```
The efficiency of [`str_replace`](https://www.php.net/manual/en/function.str-replace.php) depends on the size of the parameters that are passed to it, but since all possible rewriting parameters are passed, not just the one or two that are actually used, this does not affect performance.
For custom post types `get_permalink` refers to [`get_post_permalink`](https://developer.wordpress.org/reference/functions/get_post_permalink/), which involves more calculations anyway, but essentially winds down to the same search and replace. |
249,485 | <p>Sorry for the noob question.</p>
<p>Is a text-domain necessary for a child theme? I am building a simple child theme with no text-domain declared. So, when I use strings which are to be translated, should I use the parent theme text-domain (yes parent theme has text-domain loaded and also has .mo/.po files).</p>
<p>For example adding this line in my child theme template </p>
<pre><code><?php __('Some String', 'parent-text-domain');>
</code></pre>
<p>Will be above string be translated?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 249522,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p><strong>TL;DR:</strong> If you use strings that are in the parent theme, exaclty how they are used in parent t... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88136/"
] | Sorry for the noob question.
Is a text-domain necessary for a child theme? I am building a simple child theme with no text-domain declared. So, when I use strings which are to be translated, should I use the parent theme text-domain (yes parent theme has text-domain loaded and also has .mo/.po files).
For example adding this line in my child theme template
```
<?php __('Some String', 'parent-text-domain');>
```
Will be above string be translated?
Thanks in advance | **TL;DR:** If you use strings that are in the parent theme, exaclty how they are used in parent theme, you don't need to have a text domain for your child theme.
But if you use strings that aren't used in parent theme, to make them translatable, you'll need another text domain with related translation (`.mo`) files.
---
Translation workflow
--------------------
When WordPress encounter a string in a translatation function it:
1. Checks if a translation for required text domain has been loaded (via [`load_plugin_textdomain`](https://developer.wordpress.org/reference/functions/load_plugin_textdomain/) or [`load_theme_textdomain`](https://developer.wordpress.org/reference/functions/load_theme_textdomain/) or [`load_textdomain`](https://developer.wordpress.org/reference/functions/load_textdomain/)), if so go to point *3.*
2. Checks if translations folder (by default `wp-content/languages`) contains a matching textdomain file. Matching textdomain file is `"{$domain}-{$locale}.mo"` where `$domain` is the text domain of the string to translate and `$locale` is the current locale for the website. If that file is not found the original string is returned, otherwise it is loaded and WP forwards to next point.
3. When the textdomain is loaded, WP looks if the required string is contained in that file, if not the original string is returned, otherwiseWP forwards to next point.
4. If the found translated string needs some singular / plural resolution (e.g. when using [`_n()`](https://developer.wordpress.org/reference/functions/_n/)) those are done. Otherwise WP forwards to next point.
5. Filter hooks are applied on the translated string (see <https://developer.wordpress.org/?s=gettext&post_type%5B%5D=wp-parser-hook>) and finally the result is returned.
So?
---
When you use parent theme text domain in translation function from child theme (assuming parent theme ships and loads the textdomain file, or it has a translation file in translations folder), WordPress will arrive at point *3.* in the list above, and so if the string is available in the file (because used in parent theme) it will be translated, otherwise not so.
It means that custom strings in parent theme needs own translation file.
In theory, it is possible to use parent textdomain in another translation file, because WordPress is capable to load more times the same text domain, "merging" them, but that has issues because only one file may exists in the format `"{$domain}-{$locale}.mo"` in translation folders (see point *2.* in the list above).
So, in conclusion, the only viable way to make a child theme translatable, if it contains strings not used in parent theme, is to use own text domain and own translation file. |
249,505 | <p>I need to get all meta keys/custom fields that are assigned to a post type.</p>
<p>I don't want to get the <code>post_meta</code> values for <code>post_meta</code> assigned to a particular post, or to all posts of a post type.</p>
<p>But, I want to get all possible custom fields that are 'assigned' to a post type. </p>
<p>I have looked and I am starting to worry that it's not possible, as maybe <code>post_meta</code> isn't 'registered' but only appears in the database when a post is saved?</p>
<p>I want to get all post meta information for a post type, in the same way I can get all taxonomies' information, assigned to a post type.</p>
<p>I want to be able to do:</p>
<pre><code>get_post_meta_information_for_post_type($post_type);
</code></pre>
<p>and get something like:</p>
<pre><code>array('custom_meta_key_1', 'custom_meta_key_2);
</code></pre>
<p>... regardless of whether or not there is even one single existing post of that post type.</p>
<p>Please tell me it's possible (and how to do it :))?</p>
<p>Thanks</p>
| [
{
"answer_id": 249508,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>query all posts in the post type and then get the meta keys from the posts e.g.</p>\n\n<p><strong>Not ... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66961/"
] | I need to get all meta keys/custom fields that are assigned to a post type.
I don't want to get the `post_meta` values for `post_meta` assigned to a particular post, or to all posts of a post type.
But, I want to get all possible custom fields that are 'assigned' to a post type.
I have looked and I am starting to worry that it's not possible, as maybe `post_meta` isn't 'registered' but only appears in the database when a post is saved?
I want to get all post meta information for a post type, in the same way I can get all taxonomies' information, assigned to a post type.
I want to be able to do:
```
get_post_meta_information_for_post_type($post_type);
```
and get something like:
```
array('custom_meta_key_1', 'custom_meta_key_2);
```
... regardless of whether or not there is even one single existing post of that post type.
Please tell me it's possible (and how to do it :))?
Thanks | Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.
The function below is less expensive and using the wp native function [get\_post\_custom\_keys()](https://codex.wordpress.org/Function_Reference/get_post_custom_keys)
```
if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :
function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {
$meta_keys = array();
$posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );
foreach ( $posts as $post ) {
$post_meta_keys = get_post_custom_keys( $post->ID );
$meta_keys = array_merge( $meta_keys, $post_meta_keys );
}
// Use array_unique to remove duplicate meta_keys that we received from all posts
// Use array_values to reset the index of the array
return array_values( array_unique( $meta_keys ) );
}
endif;
```
You may use the $sample\_size param to include more posts in the loop.
Hope it helps someone. |
249,512 | <p>I've got the opposite problem a lot of people can when switching servers. All the pages work fine, EXCEPT the home page, which is generating a 404. It's just the blog URL by itself (mysite.com/blogfolder/). Wordpress is installed in a folder in the site root, and worked fine at the old host. htaccess is all what it is supposed to be for this kind of installation. What could cause this??</p>
| [
{
"answer_id": 249508,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>query all posts in the post type and then get the meta keys from the posts e.g.</p>\n\n<p><strong>Not ... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109108/"
] | I've got the opposite problem a lot of people can when switching servers. All the pages work fine, EXCEPT the home page, which is generating a 404. It's just the blog URL by itself (mysite.com/blogfolder/). Wordpress is installed in a folder in the site root, and worked fine at the old host. htaccess is all what it is supposed to be for this kind of installation. What could cause this?? | Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.
The function below is less expensive and using the wp native function [get\_post\_custom\_keys()](https://codex.wordpress.org/Function_Reference/get_post_custom_keys)
```
if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :
function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {
$meta_keys = array();
$posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );
foreach ( $posts as $post ) {
$post_meta_keys = get_post_custom_keys( $post->ID );
$meta_keys = array_merge( $meta_keys, $post_meta_keys );
}
// Use array_unique to remove duplicate meta_keys that we received from all posts
// Use array_values to reset the index of the array
return array_values( array_unique( $meta_keys ) );
}
endif;
```
You may use the $sample\_size param to include more posts in the loop.
Hope it helps someone. |
249,513 | <p>I have a weird issue on <a href="https://meta-game.org/" rel="nofollow noreferrer">my site that's only affecting mobile</a>. If you scroll down past the black "What's Hot" section, you'll see the standard posts with featured images. Now, if you refresh the page, the standard posts after the "What's Hot" section are missing the featured images. Nothing shows up in the apache or wordpress logs, and if you browse in a private session, then the featured images appear. This leads me to believe it's a caching issue, but I don't know how to proceed from there.</p>
<p>Another side note, I really noticed this when I swapped over to HTTPS, and I'm serving mixed content (images over http, everything else over https for performance). Here are my rewrite rules from my .htaccess (I just ripped them from a tutorial):</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I have verified that this is affecting Android 6.0.1 on a handful of devices, as well as some variations of iPhone. At this point, I really don't know how to proceed.</p>
| [
{
"answer_id": 249695,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>The images there you load is always to big for teh view screen, as example this image - <code>https://meta-game.o... | 2016/12/16 | [
"https://wordpress.stackexchange.com/questions/249513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107325/"
] | I have a weird issue on [my site that's only affecting mobile](https://meta-game.org/). If you scroll down past the black "What's Hot" section, you'll see the standard posts with featured images. Now, if you refresh the page, the standard posts after the "What's Hot" section are missing the featured images. Nothing shows up in the apache or wordpress logs, and if you browse in a private session, then the featured images appear. This leads me to believe it's a caching issue, but I don't know how to proceed from there.
Another side note, I really noticed this when I swapped over to HTTPS, and I'm serving mixed content (images over http, everything else over https for performance). Here are my rewrite rules from my .htaccess (I just ripped them from a tutorial):
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I have verified that this is affecting Android 6.0.1 on a handful of devices, as well as some variations of iPhone. At this point, I really don't know how to proceed. | [](https://i.stack.imgur.com/rweR4.png)
The images not being loaded are prefixed with the domain `https://i2.wp.com`
This is the [CDN](https://en.wikipedia.org/wiki/Content_delivery_network) used when you activate the **PHOTON module** in the [**Jetpack Plugin**](https://wordpress.org/plugins/jetpack/).
If you deactivate the **PHOTON module** or deactivate the [**Jetpack Plugin**](https://wordpress.org/plugins/jetpack/), you should be rid of the issue. |
249,601 | <p>I have a function I'm using to display a login notification when a user without access tries to view a single post. The function also displays the post excerpt publicly on archive, widgets, etc , but shows the login notification only when the full post is viewed, i.e. <code>is_singular</code></p>
<p>This basically allows users without access to view a snippet of the post on archive pages, but when they click & try to view the full post they're prompted with a notification to login or register. </p>
<p>The issue I'm having is that when using a related posts widget, the login notification is displayed when it shouldn't be. I'm pretty sure it has to do with how I'm defining the post variable in my function which is causing it to not differentiate between posts displayed as excerpts in the widget vs the full single post. Looking for some insight. </p>
<p><strong>Content Protection function:</strong> </p>
<pre><code>/*Show Excerpt for Protected Content*/
//Show mm content even if the user doesn't have access
function customContentProtection($data)
{
error_log('customContentProtection');
return true;
}
add_filter('mm_bypass_content_protection', 'customContentProtection');
//then we add the filters for the archive content
add_filter( 'the_content', 'sbm_mm_content_filter' );
function sbm_mm_content_filter( $content ) {
global $post;
global $post_id;
if ( !is_singular())
return $content;
$new_content = $content;
// define what users without access view
if ( mm_access_decision(array("access"=>"true")) != true ){
//Need to apply a filter to get the excerpt if the template doesn't include it
$new_content = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
/*
//This is where we output the excerpt & login form
echo '<div>' . $new_content . '</div><br><div>' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') .'</div>';
*/
//Instead of the excerpt let's output a blurred text image
$url = site_url();
echo
'<div class="no-access-wrapper">
<div class="no-access">
<img src=" ' . $url . '/wp-content/themes/splash-child/images/blurred-text.png"></div>
<div class="no-access-top">
<h3 style="text-align:center;">This content is for members only. Please login or sign up.</h3>
' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') . '
<br>
<p style="text-align:center;"> If you are already logged in and are having trouble viewing this content, please <a href="mailto: support@sportsbettingmax.com">contact support</a></p>
</div>
</div>';
}
else return $new_content;
}
</code></pre>
<p>Here's the section of my single.php file that outputs the related posts widget: </p>
<pre><code> <?php
}
$related_post_number = $bdp_settings['related_post_number'];
$col_class = '';
if ($related_post_number == 2) {
$post_perpage = 2;
}
if ($related_post_number == 3) {
$post_perpage = 3;
}
if ($related_post_number == 4) {
$post_perpage = 4;
}
$related_post_by = $bdp_settings['related_post_by'];
$title = $bdp_settings['related_post_title'];
if (isset($bdp_settings['display_related_post']) && $bdp_settings['display_related_post'] == 1) {
$related_post_content_length = isset($bdp_settings['related_post_content_length']) ? $bdp_settings['related_post_content_length'] : '';
$args = array();
if ($related_post_by == "category") {
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts that will be displayed. 'caller_get_posts' => 1,
);
}
} elseif ($related_post_by == "tag") {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach ($tags as $individual_tag)
$tag_ids[] = $individual_tag->term_id;
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts to display.
);
}
}
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
?>
<div class="related_post_wrap">
<?php
do_action('bdp_related_post_detail', $theme, $post_perpage, $related_post_by, $title, $related_post_content_length);
?>
</div>
<?php
}
}
// If comments are open or we have at least one comment, load up the comment template.
if ($bdp_settings['display_comment'] == 1) {
if (comments_open() || get_comments_number()) {
comments_template();
}
}
// End of the loop.
endwhile;
if ($theme == "offer_blog" || $theme == "winter") {
echo '</div>';
}
?>
</div>
<?php do_action('bdp_after_single_page'); ?>
</main><!-- .site-main -->
</div><!-- .content-area -->
</code></pre>
| [
{
"answer_id": 249594,
"author": "Rikki B",
"author_id": 109162,
"author_profile": "https://wordpress.stackexchange.com/users/109162",
"pm_score": 3,
"selected": true,
"text": "<p>It was a stupid question, I just realized, if I just create a custom shortcode for it, the plugin will not w... | 2016/12/18 | [
"https://wordpress.stackexchange.com/questions/249601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109165/"
] | I have a function I'm using to display a login notification when a user without access tries to view a single post. The function also displays the post excerpt publicly on archive, widgets, etc , but shows the login notification only when the full post is viewed, i.e. `is_singular`
This basically allows users without access to view a snippet of the post on archive pages, but when they click & try to view the full post they're prompted with a notification to login or register.
The issue I'm having is that when using a related posts widget, the login notification is displayed when it shouldn't be. I'm pretty sure it has to do with how I'm defining the post variable in my function which is causing it to not differentiate between posts displayed as excerpts in the widget vs the full single post. Looking for some insight.
**Content Protection function:**
```
/*Show Excerpt for Protected Content*/
//Show mm content even if the user doesn't have access
function customContentProtection($data)
{
error_log('customContentProtection');
return true;
}
add_filter('mm_bypass_content_protection', 'customContentProtection');
//then we add the filters for the archive content
add_filter( 'the_content', 'sbm_mm_content_filter' );
function sbm_mm_content_filter( $content ) {
global $post;
global $post_id;
if ( !is_singular())
return $content;
$new_content = $content;
// define what users without access view
if ( mm_access_decision(array("access"=>"true")) != true ){
//Need to apply a filter to get the excerpt if the template doesn't include it
$new_content = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
/*
//This is where we output the excerpt & login form
echo '<div>' . $new_content . '</div><br><div>' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') .'</div>';
*/
//Instead of the excerpt let's output a blurred text image
$url = site_url();
echo
'<div class="no-access-wrapper">
<div class="no-access">
<img src=" ' . $url . '/wp-content/themes/splash-child/images/blurred-text.png"></div>
<div class="no-access-top">
<h3 style="text-align:center;">This content is for members only. Please login or sign up.</h3>
' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') . '
<br>
<p style="text-align:center;"> If you are already logged in and are having trouble viewing this content, please <a href="mailto: support@sportsbettingmax.com">contact support</a></p>
</div>
</div>';
}
else return $new_content;
}
```
Here's the section of my single.php file that outputs the related posts widget:
```
<?php
}
$related_post_number = $bdp_settings['related_post_number'];
$col_class = '';
if ($related_post_number == 2) {
$post_perpage = 2;
}
if ($related_post_number == 3) {
$post_perpage = 3;
}
if ($related_post_number == 4) {
$post_perpage = 4;
}
$related_post_by = $bdp_settings['related_post_by'];
$title = $bdp_settings['related_post_title'];
if (isset($bdp_settings['display_related_post']) && $bdp_settings['display_related_post'] == 1) {
$related_post_content_length = isset($bdp_settings['related_post_content_length']) ? $bdp_settings['related_post_content_length'] : '';
$args = array();
if ($related_post_by == "category") {
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts that will be displayed. 'caller_get_posts' => 1,
);
}
} elseif ($related_post_by == "tag") {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach ($tags as $individual_tag)
$tag_ids[] = $individual_tag->term_id;
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts to display.
);
}
}
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
?>
<div class="related_post_wrap">
<?php
do_action('bdp_related_post_detail', $theme, $post_perpage, $related_post_by, $title, $related_post_content_length);
?>
</div>
<?php
}
}
// If comments are open or we have at least one comment, load up the comment template.
if ($bdp_settings['display_comment'] == 1) {
if (comments_open() || get_comments_number()) {
comments_template();
}
}
// End of the loop.
endwhile;
if ($theme == "offer_blog" || $theme == "winter") {
echo '</div>';
}
?>
</div>
<?php do_action('bdp_after_single_page'); ?>
</main><!-- .site-main -->
</div><!-- .content-area -->
``` | It was a stupid question, I just realized, if I just create a custom shortcode for it, the plugin will not wrap it in `<p>` tags then, or even better still just create it as a plugin of it's own. |
249,612 | <p>Want to use a different featured image size for a custom post type and exclude it from main blog loop. And also want to display it on specific page.</p>
<p>What will be the fastest way to achieve this? With code mess up and plugins?</p>
<p>Prefer a code snippet solution, but main issue it should work out-of-box, as fast solution is a priority.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 249618,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 1,
"selected": false,
"text": "<p>Make a custom post-type template with the specific featured size in the template or appropriate css applied to t... | 2016/12/18 | [
"https://wordpress.stackexchange.com/questions/249612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32880/"
] | Want to use a different featured image size for a custom post type and exclude it from main blog loop. And also want to display it on specific page.
What will be the fastest way to achieve this? With code mess up and plugins?
Prefer a code snippet solution, but main issue it should work out-of-box, as fast solution is a priority.
Thanks in advance. | This might help - [Set featured image size for a custom post type](https://wordpress.stackexchange.com/questions/32811/set-featured-image-size-for-a-custom-post-type?rq=1),
>
> Just add a new image size
>
>
>
> ```
> add_image_size( 'companies_thumb', 120, 120, true);
>
> ```
>
> Then in the post type template for companies you just call the thumb
> you defined.
>
>
>
> ```
> <?php the_post_thumbnail('companies_thumb'); ?>
>
> ```
>
> |
249,622 | <p>How can I check if post with name for example Weather exists? If not I want to create it.</p>
<pre><code>function such_post_exists($title) {
global $wpdb;
$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
if ( !empty ( $title ) ) {
return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}
return 0;
}
</code></pre>
| [
{
"answer_id": 249624,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": true,
"text": "<p>Wordpress has a <code>post_exists</code> function that returns the post ID or 0 otherwise.\nSo you can do</p>\n\... | 2016/12/18 | [
"https://wordpress.stackexchange.com/questions/249622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105218/"
] | How can I check if post with name for example Weather exists? If not I want to create it.
```
function such_post_exists($title) {
global $wpdb;
$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
if ( !empty ( $title ) ) {
return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}
return 0;
}
``` | Wordpress has a `post_exists` function that returns the post ID or 0 otherwise.
So you can do
```
if ( 0 === post_exists( $title ) ) {
**YOUR_CODE_HERE**
}
``` |
249,630 | <p>This,</p>
<pre><code>if( has_term( 'jazz', 'genre' ) ) {
// do something
}
</code></pre>
<p>will check if a post has the term <code>jazz</code> from the custom taxonomy <code>genre</code>. But how to check if a post belongs to a custom taxonomy <code>genre</code>? No matter whatever term it has, as long as it has something from the <code>genre</code> taxonomy, it will check.</p>
<p>So something like this,</p>
<pre><code>if ( has_taxonomy('genre') ) {
// whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them.
}
</code></pre>
| [
{
"answer_id": 249634,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if ( has_term('', 'genre') ) {\n // whether it's jazz, blues, rock and roll; doesn't matter as long ... | 2016/12/18 | [
"https://wordpress.stackexchange.com/questions/249630",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13291/"
] | This,
```
if( has_term( 'jazz', 'genre' ) ) {
// do something
}
```
will check if a post has the term `jazz` from the custom taxonomy `genre`. But how to check if a post belongs to a custom taxonomy `genre`? No matter whatever term it has, as long as it has something from the `genre` taxonomy, it will check.
So something like this,
```
if ( has_taxonomy('genre') ) {
// whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them.
}
``` | You can have the term input empty, e.g.
```
if( has_term( '', 'genre' ) ) {
// do something
}
```
to see if the current post object has any terms in the genre taxonomy.
It uses [`is_object_in_term()`](https://developer.wordpress.org/reference/functions/is_object_in_term/) where:
>
> The given terms are checked against the object’s terms’ term\_ids,
> names and slugs. Terms given as integers will only be checked against
> the object’s terms’ term\_ids. If no terms are given, determines if
> object is associated with any terms in the given taxonomy.
>
>
> |
249,670 | <p>I'm trying to check the output of a variable in my functions.php file that runs after a new woocommerce order. The code will get the order time from a new order and store it in a variable for me to use elsewhere the code being:</p>
<pre><code>$meeting_time = wc_get_order_item_meta($order_id, 'Time');
print_r($meeting_time);
</code></pre>
<p>I've tried a few ways to print the information:</p>
<ul>
<li>print_r </li>
<li>javascript popup box</li>
<li>writing to error log</li>
</ul>
<p>but I can't seem to get any of these to work as my php knowledge isn't very good.</p>
<p>I want to be able to see the output of the variable to make sure it's returning what I want.</p>
<p>Is anyone able to assist me?</p>
<p>Please and thankyou.</p>
| [
{
"answer_id": 249672,
"author": "TCode",
"author_id": 109129,
"author_profile": "https://wordpress.stackexchange.com/users/109129",
"pm_score": 0,
"selected": false,
"text": "<p>wc_get_order_item_meta function requires an Order Item's ID, not the Order ID.</p>\n\n<pre><code>wc_get_order... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107852/"
] | I'm trying to check the output of a variable in my functions.php file that runs after a new woocommerce order. The code will get the order time from a new order and store it in a variable for me to use elsewhere the code being:
```
$meeting_time = wc_get_order_item_meta($order_id, 'Time');
print_r($meeting_time);
```
I've tried a few ways to print the information:
* print\_r
* javascript popup box
* writing to error log
but I can't seem to get any of these to work as my php knowledge isn't very good.
I want to be able to see the output of the variable to make sure it's returning what I want.
Is anyone able to assist me?
Please and thankyou. | You can use [`var_dump()`](http://php.net/manual/en/function.var-dump.php) instead of `print_r()` - you get the type and the value of the variable and it will also work when your variable holds `FALSE` or `NULL`.
```
print_r( false ); # doesn't output anything
var_dump( false ); # output: bool(false)
print_r( NULL ); # doesn't output anything
var_dump( NULL ); # output: NULL
```
If you have arrays or objects to inspect, you could use a plugin like [Kint Debugger](https://wordpress.org/plugins/kint-debugger/) to format the output into a more readable format. |
249,671 | <p>Very basic question, but I couldn't find an answer.</p>
<p>I am using the WP CLI post get command: <a href="https://wp-cli.org/commands/post/get/" rel="nofollow noreferrer">https://wp-cli.org/commands/post/get/</a></p>
<p>One of the option is [--field=], but I can't find in the doc the list of allowed values for this field.</p>
<p>What am I missing?</p>
| [
{
"answer_id": 249681,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 3,
"selected": true,
"text": "<p>The list of fields is available on the <a href=\"https://wp-cli.org/commands/post/list/#available-fields\" rel... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44388/"
] | Very basic question, but I couldn't find an answer.
I am using the WP CLI post get command: <https://wp-cli.org/commands/post/get/>
One of the option is [--field=], but I can't find in the doc the list of allowed values for this field.
What am I missing? | The list of fields is available on the [`wp post list`](https://wp-cli.org/commands/post/list/#available-fields) page.
>
> These fields will be displayed by default for each post:
>
>
>
> ```
> ID
> post_title
> post_name
> post_date
> post_status
>
> ```
>
> These fields are optionally available:
>
>
>
> ```
> post_author
> post_date_gmt
> post_content
> post_excerpt
> comment_status
> ping_status
> post_password
> to_ping
> pinged
> post_modified
> post_modified_gmt
> post_content_filtered
> post_parent
> guid
> menu_order
> post_type
> post_mime_type
> comment_count
> filter
> url
>
> ```
>
> |
249,677 | <p>I use Wordpress 4.7 and I installed an accessibility module. This module requires pasting the following php code block before the body. I went through the mother-theme php files but didn't find something like html.php or html.tpl ... Should this file be created (and maybe also declared) somewhere?</p>
<pre><code><?php if(function_exists('acp_toolbar') ) { acp_toolbar(); }?>
</code></pre>
| [
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I use Wordpress 4.7 and I installed an accessibility module. This module requires pasting the following php code block before the body. I went through the mother-theme php files but didn't find something like html.php or html.tpl ... Should this file be created (and maybe also declared) somewhere?
```
<?php if(function_exists('acp_toolbar') ) { acp_toolbar(); }?>
``` | You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page. |
249,697 | <p>I want to display a loop in my page-projets.php file.</p>
<pre><code><div class="loop center">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part('content');
endwhile;
get_template_part('pagination');
endif; ?>
</div>
</code></pre>
<p>However, on the resulting page, I can only see the page itself within the loop. Sometimes, it even returns a blank result : <a href="http://riehling.mrcoolblog.com/projets/" rel="nofollow noreferrer">http://riehling.mrcoolblog.com/projets/</a></p>
<p>Could you please tell me what's wrong here ?</p>
<p>Regards,
Greg</p>
| [
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88389/"
] | I want to display a loop in my page-projets.php file.
```
<div class="loop center">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part('content');
endwhile;
get_template_part('pagination');
endif; ?>
</div>
```
However, on the resulting page, I can only see the page itself within the loop. Sometimes, it even returns a blank result : <http://riehling.mrcoolblog.com/projets/>
Could you please tell me what's wrong here ?
Regards,
Greg | You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page. |
249,707 | <p>Something really weird happened. I want to change the color of this text but the index file has an !important there and when i change the color on my style.css file it doesn't work. What can i do to over ride that !important.</p>
<p>This is how it looks in my css file</p>
<pre><code>h1.entry-title {
color: #9A7B5C ;
}
</code></pre>
<p>i want that brown color but the index file isn't letting me change it from yellow. Please help and this how the index file looks like </p>
<pre><code>DIV SECTION DIV.container NAV A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry HEADER.entry-header H1.entry-title, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P, DIV P STRONG EM A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P.ui-draggable.ui-draggable-handle {
color: #ffe206 !important; }
</code></pre>
| [
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109224/"
] | Something really weird happened. I want to change the color of this text but the index file has an !important there and when i change the color on my style.css file it doesn't work. What can i do to over ride that !important.
This is how it looks in my css file
```
h1.entry-title {
color: #9A7B5C ;
}
```
i want that brown color but the index file isn't letting me change it from yellow. Please help and this how the index file looks like
```
DIV SECTION DIV.container NAV A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry HEADER.entry-header H1.entry-title, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P, DIV P STRONG EM A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P.ui-draggable.ui-draggable-handle {
color: #ffe206 !important; }
``` | You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page. |
249,712 | <p>I originally made <a href="https://wordpress.stackexchange.com/questions/249357/ninja-forms-shortcode-not-producing-intended-results-in-custom-wordpress-theme">this post</a>, thinking that my problem was specific to the Ninja Forms plugin (the original post was obviously put on hold, for being off-topic). My reason for thinking so, was that WordPress' native gallery shortcode was working correctly, but it would seem that the issue affects <strong>all</strong> plugin shortcodes.</p>
<p>As this is no longer an issue with a specific plugin, but WordPress's ability to execute plugin shortcodes -- --, I've taken the liberty to assume that it is now considered on-topic.</p>
<p>Even with an empty <em>functions.php</em> file and the following as my only code, the issue still persists.</p>
<pre><code><?php
if (have_posts()) : while (have_posts()) : the_post();
the_content();
endwhile;
endif;
?>
</code></pre>
<p>When inspecting the page, this appears to output <strong>some</strong> of what it's supposed to, in the form of a script or div, but it's as if the plugins are never rendered, despite being initialized.</p>
<p>I've been stuck here for a few days now, so if anyone could give me a push in the right direction, that would be amazing!</p>
<p><strong>Note:</strong> I apologize if this is still considered to be off-topic. In case it is, please disregard this post.</p>
| [
{
"answer_id": 249731,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 0,
"selected": false,
"text": "<p>You should try to active the default wordpress theme like twenty eleven or like that and then see... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109018/"
] | I originally made [this post](https://wordpress.stackexchange.com/questions/249357/ninja-forms-shortcode-not-producing-intended-results-in-custom-wordpress-theme), thinking that my problem was specific to the Ninja Forms plugin (the original post was obviously put on hold, for being off-topic). My reason for thinking so, was that WordPress' native gallery shortcode was working correctly, but it would seem that the issue affects **all** plugin shortcodes.
As this is no longer an issue with a specific plugin, but WordPress's ability to execute plugin shortcodes -- --, I've taken the liberty to assume that it is now considered on-topic.
Even with an empty *functions.php* file and the following as my only code, the issue still persists.
```
<?php
if (have_posts()) : while (have_posts()) : the_post();
the_content();
endwhile;
endif;
?>
```
When inspecting the page, this appears to output **some** of what it's supposed to, in the form of a script or div, but it's as if the plugins are never rendered, despite being initialized.
I've been stuck here for a few days now, so if anyone could give me a push in the right direction, that would be amazing!
**Note:** I apologize if this is still considered to be off-topic. In case it is, please disregard this post. | As was pointed out by [Michael](https://wordpress.stackexchange.com/users/4884/michael), I had been missing the `wp_head()` and `wp_footer()` functions.
To anyone who might be in the same boat as I, you can have a look at the function references [here (head)](https://codex.wordpress.org/Function_Reference/wp_head) and [here (footer)](https://codex.wordpress.org/Function_Reference/wp_footer).
Thank you, to anyone who took their time to help me out, even if all they did was read the question. I'm glad we reached a conclusion so quickly! |
249,744 | <p>Brand new site. Not MU. No matter what I do, I cannot get a file uploaded that exceeds 2MB. I'm running a localhost server with WordPress 4.3.1</p>
<p>I've modified both relevant settings in the the site's <code>php.ini</code> as:</p>
<pre><code>upload_max_filesize = 64M
post_max_size = 64M
</code></pre>
<p>However, I'm still getting the message when trying to upload a plugin that's 2.5M</p>
<blockquote>
<p>The uploaded file exceeds the upload_max_filesize directive in
php.ini.</p>
</blockquote>
<p>Also, when I go to "Media > Add New", I get the message:</p>
<blockquote>
<p>Maximum upload file size: 2 MB.</p>
</blockquote>
<p>My htaccess file is the default and has no mention of max upload size.</p>
<p>What gives? Is it a requirement to restart anything after modifying the site's php.ini? If so, I could not find a restart command on my phpmyadmin panel.</p>
| [
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version con... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/366/"
] | Brand new site. Not MU. No matter what I do, I cannot get a file uploaded that exceeds 2MB. I'm running a localhost server with WordPress 4.3.1
I've modified both relevant settings in the the site's `php.ini` as:
```
upload_max_filesize = 64M
post_max_size = 64M
```
However, I'm still getting the message when trying to upload a plugin that's 2.5M
>
> The uploaded file exceeds the upload\_max\_filesize directive in
> php.ini.
>
>
>
Also, when I go to "Media > Add New", I get the message:
>
> Maximum upload file size: 2 MB.
>
>
>
My htaccess file is the default and has no mention of max upload size.
What gives? Is it a requirement to restart anything after modifying the site's php.ini? If so, I could not find a restart command on my phpmyadmin panel. | While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme. |
249,753 | <p>I am using the REST API to publish posts outside of WordPress, and have run into a problem where not all of my shortcodes are getting processed. Specifically, most of my plugins' shortcodes are getting processed but nothing from visual composer is getting converted to HTML. I find that if I var_dump my REST API's post data function on the front end of the WordPress site itself (blank theme, theme is literally 'var_dump this function'), the shortcodes for VC do get processed.</p>
<p>I am not sure what I am doing wrong here, but here is my code for the REST API return:</p>
<pre><code>function return_page_single( WP_REST_Request $request ) {
$page_id = $request->get_param( 'page' );
$args = array(
'id' => $page_id,
'post_type' => 'page',
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$page = $query->posts;
$page_content = $page[0]->post_content;
$page_content = apply_filters( 'the_content', $page_content );
$page_content = do_shortcode( $page_content );
$page[0]->post_content = $page_content;
$query_return['page'] = $page;
$query_return['query'] = $query->query;
}
wp_reset_postdata();
return $query_return;
}
</code></pre>
<p>If I dump the contents of my REST API result, I get shortcodes for VC but everything else processes.</p>
<p>If I place the following in my theme: </p>
<pre><code>var_dump( return_page_single( $request ) );
</code></pre>
<p>I get the fully processed post content.</p>
<p>I don't have a live example as this is being developed internally but if it helps to troubleshoot I can probably set something up.</p>
| [
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version con... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249753",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109253/"
] | I am using the REST API to publish posts outside of WordPress, and have run into a problem where not all of my shortcodes are getting processed. Specifically, most of my plugins' shortcodes are getting processed but nothing from visual composer is getting converted to HTML. I find that if I var\_dump my REST API's post data function on the front end of the WordPress site itself (blank theme, theme is literally 'var\_dump this function'), the shortcodes for VC do get processed.
I am not sure what I am doing wrong here, but here is my code for the REST API return:
```
function return_page_single( WP_REST_Request $request ) {
$page_id = $request->get_param( 'page' );
$args = array(
'id' => $page_id,
'post_type' => 'page',
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$page = $query->posts;
$page_content = $page[0]->post_content;
$page_content = apply_filters( 'the_content', $page_content );
$page_content = do_shortcode( $page_content );
$page[0]->post_content = $page_content;
$query_return['page'] = $page;
$query_return['query'] = $query->query;
}
wp_reset_postdata();
return $query_return;
}
```
If I dump the contents of my REST API result, I get shortcodes for VC but everything else processes.
If I place the following in my theme:
```
var_dump( return_page_single( $request ) );
```
I get the fully processed post content.
I don't have a live example as this is being developed internally but if it helps to troubleshoot I can probably set something up. | While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme. |
249,761 | <p>I have create a form on a wordpress page, and I'm trying to pass the values of the form to a php page, so I can send an email with that information, but I don't know how to create the php page, in what folder do I have to save the page.</p>
<p>Thank you (fist time using wordpress);</p>
<p>This is my form:
And I have a different page(send-email) that will collect the data. </p>
<p>I know how to do the code for the send-email page..I just nee dto know where to save the php page.</p>
<pre><code><form method="get" action="send-email.php" name="emailForm" onsubmit="return validate()">
<div class="form-group">
<label for="name">Name<span id="req">*</span></label><br>
<input type="text" class="form-control" id="name" name="name" placeholder="Quantum Management" value="">
</div>
<div class="form-group">
<label for="tel">Phone Number<span id="reqTel">*</span></label><br>
<input type="text" class="form-control" id="tel" name="tel" placeholder="(999) 123-4567" value="" >
</div>
<div class="form-group">
<label for="email">Email<span id="reqEmail">*</span></label><br>
<input type="text" class="form-control" id="email" name="email" placeholder="example@example.com" value="" >
</div>
<div class="form-group">
<label for="questions">Questions<span id="reqQuest">*</span></label><br>
<textarea class="form-control" rows="7" cols="8" id="questions" name="questions" placeholder="Questions" ></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="submit" value="yes">Submit</button>
</div>
</form>
</code></pre>
| [
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version con... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109259/"
] | I have create a form on a wordpress page, and I'm trying to pass the values of the form to a php page, so I can send an email with that information, but I don't know how to create the php page, in what folder do I have to save the page.
Thank you (fist time using wordpress);
This is my form:
And I have a different page(send-email) that will collect the data.
I know how to do the code for the send-email page..I just nee dto know where to save the php page.
```
<form method="get" action="send-email.php" name="emailForm" onsubmit="return validate()">
<div class="form-group">
<label for="name">Name<span id="req">*</span></label><br>
<input type="text" class="form-control" id="name" name="name" placeholder="Quantum Management" value="">
</div>
<div class="form-group">
<label for="tel">Phone Number<span id="reqTel">*</span></label><br>
<input type="text" class="form-control" id="tel" name="tel" placeholder="(999) 123-4567" value="" >
</div>
<div class="form-group">
<label for="email">Email<span id="reqEmail">*</span></label><br>
<input type="text" class="form-control" id="email" name="email" placeholder="example@example.com" value="" >
</div>
<div class="form-group">
<label for="questions">Questions<span id="reqQuest">*</span></label><br>
<textarea class="form-control" rows="7" cols="8" id="questions" name="questions" placeholder="Questions" ></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="submit" value="yes">Submit</button>
</div>
</form>
``` | While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme. |
249,766 | <p>I have a website that I am updating, it has over 400 posts so updating these manually isn't a very good option. The theme that was used is no longer supported, it has a custom field setup for the featured image. I want to convert that featured image to the WordPress featured image. How can I do this? In the database, the url for the images are stored under wp_postmeta and the meta_key is lifestyle_post_image.</p>
| [
{
"answer_id": 249767,
"author": "mayersdesign",
"author_id": 106965,
"author_profile": "https://wordpress.stackexchange.com/users/106965",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://wordpress.org/plugins/quick-featured-images/\" rel=\"nofollow noreferrer\">https://... | 2016/12/19 | [
"https://wordpress.stackexchange.com/questions/249766",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109261/"
] | I have a website that I am updating, it has over 400 posts so updating these manually isn't a very good option. The theme that was used is no longer supported, it has a custom field setup for the featured image. I want to convert that featured image to the WordPress featured image. How can I do this? In the database, the url for the images are stored under wp\_postmeta and the meta\_key is lifestyle\_post\_image. | I ended up finding another post that helped me achieve what I was trying to do. <https://stackoverflow.com/questions/4371929/convert-custom-field-image-to-become-featured-image-in-wordpress>
```
$uploads = wp_upload_dir();
// Get all attachment IDs and filenames
$results = $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file'");
// Create an 'index' of attachment IDs and their filenames
$attachments = array();
foreach ($results as $row)
$attachments[ intval($row->post_id) ] = $row->meta_value;
// Get all featured images
$images = $wpdb->get_results("SELECT post_id, meta_value AS 'url' FROM $wpdb->postmeta WHERE meta_key = 'lifestyle_post_image'");
// Loop over each image and try and find attachment post
foreach ($images as $image) {
if (preg_match('#^https?://#', $image->url))
$image->url = str_replace($uploads['baseurl'], '', $image->url); // get relative URL if absolute
$filename = ltrim($image->url, '/');
if ($attachment_ID = array_search($filename, $attachments)) {
// found attachment, set post thumbnail and delete featured image
update_post_meta($image->post_id, '_thumbnail_id', $attachment_ID);
delete_post_meta($image->post_ID, 'Featured Image');
}
}
``` |
249,797 | <p>I am trying to retrieve some basic information from the Wordpress database for a theme. However, when the query runs it returns no data. If I run the query on Phpmyadmin, it works fine. Note, wp_places_locator is a table used by a third party plugin.</p>
<pre><code>function get_info($postid) {
global $wpdb;
$info = $wpdb->get_results($wpdb->prepare("SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = '$postid'"));
print_r($info);
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 249800,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>Here you've did something wrong with <code>$wpdb->table_name</code>. It will only return the default Wor... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106918/"
] | I am trying to retrieve some basic information from the Wordpress database for a theme. However, when the query runs it returns no data. If I run the query on Phpmyadmin, it works fine. Note, wp\_places\_locator is a table used by a third party plugin.
```
function get_info($postid) {
global $wpdb;
$info = $wpdb->get_results($wpdb->prepare("SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = '$postid'"));
print_r($info);
}
```
Thanks! | Here you've did something wrong with `$wpdb->table_name`. It will only return the default WordPress table names. Not custom table names. And also when you call `$wpdb->prepare` then pass the parameter as array. So your function will be like below-
```
function get_info($postid) {
global $wpdb;
// Here I assumed that your table name is '{$wpdb->prefix}places_locator'
$sql = $wpdb->prepare("SELECT post_id, address, phone, email
FROM {$wpdb->prefix}places_locator
WHERE post_id = '%d'",
array( $postid )
);
$info = $wpdb->get_results($sql);
return $info;
}
```
Now if you do `print_r` on `get_info()` with parameter post ID then it will return you value.
Use like below-
```
print_r(get_info(1)); // Here I assumed your post ID is 1
``` |
249,815 | <p>I am running a news website, most of the posts are from an Editor Account. I want to hide the author-box displaying at the bottom of the posts, only for this user. Only author box of Editor should be hidden from public.<br/>
Is there any way to hide the author box of a particular user from public, with a funtion?</p>
<p>Author box element is in loop-single.php file.
wrapped in the footer of the post,</p>
<pre><code><?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php echo $td_mod_single->get_author_box();?>
<?php echo $td_mod_single->get_item_scope_meta();?>
</code></pre>
| [
{
"answer_id": 249818,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 2,
"selected": true,
"text": "<p>If you know the data of the author, you can wrap that box with an if and the function <a href=\"https://co... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109300/"
] | I am running a news website, most of the posts are from an Editor Account. I want to hide the author-box displaying at the bottom of the posts, only for this user. Only author box of Editor should be hidden from public.
Is there any way to hide the author box of a particular user from public, with a funtion?
Author box element is in loop-single.php file.
wrapped in the footer of the post,
```
<?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php echo $td_mod_single->get_author_box();?>
<?php echo $td_mod_single->get_item_scope_meta();?>
``` | If you know the data of the author, you can wrap that box with an if and the function [get\_the\_author](https://codex.wordpress.org/Function_Reference/get_the_author)
```
if( get_the_author() == "name_of_the_author" ){
// Don't do it
}else{
// Print box
}
```
EDIT with the final answer updated:
```
<?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php
$user = get_user_by("login", "pknn"); // user object
// get_the_author() needs the display name, not the login
if( get_the_author() != $user->data->display_name ){
echo $td_mod_single->get_author_box();
}
?>
<?php echo $td_mod_single->get_item_scope_meta();?>
``` |
249,826 | <p>I have written functionality for checking if custom post title exists or not while adding post. like below:</p>
<pre><code> function wp_exist_post_by_title( $title ) {
global $wpdb;
$return = $wpdb->get_row( "SELECT ID FROM wp_dxwe_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'courses' ", 'ARRAY_N' );
if( empty( $return ) ) {
return false;
} else {
return true;
}
}
</code></pre>
<p>While adding new post my code is below:</p>
<pre><code>$check = $this->wp_exist_post_by_title( $_POST['course_title'] ) ;
if($check==true)
{
$title = '';
echo "<div class='conditional-messages'>Course Already Exists !</div>";
}
else
{
$title=$_POST['course_title'];
}
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$description = $_POST['description'];
$id = wp_insert_post($post);
update_post_meta($id, 'course_icon', $attachement_id);
update_post_meta( $id, 'inistitute_name', $institute_name);
</code></pre>
<p>While I am adding new post(course title) it is checking if post_title exists or not perfectly but my problem here is I want to check post title(course title) belongs to only one 'institute_name' because other institutes can have the same course title(custom post) too. I know I need to join 2 tables i.e. 'wp_posts' & 'wp_postmeta', but I was unable to do. can anyone please tell me how to sort out this? Thanks for any help.</p>
| [
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] | I have written functionality for checking if custom post title exists or not while adding post. like below:
```
function wp_exist_post_by_title( $title ) {
global $wpdb;
$return = $wpdb->get_row( "SELECT ID FROM wp_dxwe_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'courses' ", 'ARRAY_N' );
if( empty( $return ) ) {
return false;
} else {
return true;
}
}
```
While adding new post my code is below:
```
$check = $this->wp_exist_post_by_title( $_POST['course_title'] ) ;
if($check==true)
{
$title = '';
echo "<div class='conditional-messages'>Course Already Exists !</div>";
}
else
{
$title=$_POST['course_title'];
}
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$description = $_POST['description'];
$id = wp_insert_post($post);
update_post_meta($id, 'course_icon', $attachement_id);
update_post_meta( $id, 'inistitute_name', $institute_name);
```
While I am adding new post(course title) it is checking if post\_title exists or not perfectly but my problem here is I want to check post title(course title) belongs to only one 'institute\_name' because other institutes can have the same course title(custom post) too. I know I need to join 2 tables i.e. 'wp\_posts' & 'wp\_postmeta', but I was unable to do. can anyone please tell me how to sort out this? Thanks for any help. | You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title> |
249,827 | <p>I've been searching for a good few days now trying to get my WordPress event calendar by modern tribe working as I need it to.</p>
<p>I have hundreds of order by and delivery dates in DB each one separated by about 5-10 weeks. what I'm trying to achieve is a list where I can see the all the events starting on today's or yesterday's date.</p>
<p>This sounds simple however the problem appears to be when you query events between two dates it will query both the start and end date giving you historical events which don't need to be seen and can be confusing.</p>
<p>I believe the way to overcome this is with a wp_query and meta_query but no matter which way I try to add the meta query to sort by start date only it breaks the whole thing.</p>
<p>this is the query below any help would be awsome as I've little hair left to pull out!</p>
<pre><code> <?php
$query = new WP_Query( array( 'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => date('Y-m-d H:i:s', strtotime('-1 week')),
'compare' => 'date'
)
)
) );
if ($query->have_posts())
{
while ($query->have_posts()) : $query->the_post();
echo $query->post->EventStartDate . ' ';
echo $query->post->post_title . '</br>';
endwhile;
}
wp_reset_query();
?>
</code></pre>
<p>I've also tried changing the meta value to</p>
<pre><code> 'value' => date('Y-m-d', strtotime('-1 week')),
</code></pre>
<p>but this didnt work either...</p>
<p>Thanks</p>
| [
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91255/"
] | I've been searching for a good few days now trying to get my WordPress event calendar by modern tribe working as I need it to.
I have hundreds of order by and delivery dates in DB each one separated by about 5-10 weeks. what I'm trying to achieve is a list where I can see the all the events starting on today's or yesterday's date.
This sounds simple however the problem appears to be when you query events between two dates it will query both the start and end date giving you historical events which don't need to be seen and can be confusing.
I believe the way to overcome this is with a wp\_query and meta\_query but no matter which way I try to add the meta query to sort by start date only it breaks the whole thing.
this is the query below any help would be awsome as I've little hair left to pull out!
```
<?php
$query = new WP_Query( array( 'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => date('Y-m-d H:i:s', strtotime('-1 week')),
'compare' => 'date'
)
)
) );
if ($query->have_posts())
{
while ($query->have_posts()) : $query->the_post();
echo $query->post->EventStartDate . ' ';
echo $query->post->post_title . '</br>';
endwhile;
}
wp_reset_query();
?>
```
I've also tried changing the meta value to
```
'value' => date('Y-m-d', strtotime('-1 week')),
```
but this didnt work either...
Thanks | You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title> |
249,854 | <p>I am trying to replace the image at <a href="https://imgur.com/a/IHwaC" rel="nofollow noreferrer">http://imgur.com/a/IHwaC</a> (wont let me upload it to here for some reason) with another image but whenever I do it it just seems to make the background white and not actually do anything.
The way I change them is by uploading the image to the WordPress media library and replacing the image name with the other image name.</p>
<p><strong>My Questions:</strong></p>
<p>Am I doing something wrong when trying to upload?</p>
<p>Is my image sized wrong?</p>
<p>(I'm running WordPress on academyofperformancearts.com.)</p>
| [
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109320/"
] | I am trying to replace the image at [http://imgur.com/a/IHwaC](https://imgur.com/a/IHwaC) (wont let me upload it to here for some reason) with another image but whenever I do it it just seems to make the background white and not actually do anything.
The way I change them is by uploading the image to the WordPress media library and replacing the image name with the other image name.
**My Questions:**
Am I doing something wrong when trying to upload?
Is my image sized wrong?
(I'm running WordPress on academyofperformancearts.com.) | You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title> |
249,881 | <p>I am trying to order blog posts by 'city' first and then order by 'street_name' within each city. I can't seem to get the 'street_name' to display in alphabetical order. I am using WP_Query:</p>
<pre><code> <?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
</code></pre>
<p>),
Any ideas?</p>
| [
{
"answer_id": 249894,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p><code>meta_query</code> and <code>orderby</code> are seperate parameters, you just put them together in an a... | 2016/12/20 | [
"https://wordpress.stackexchange.com/questions/249881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109345/"
] | I am trying to order blog posts by 'city' first and then order by 'street\_name' within each city. I can't seem to get the 'street\_name' to display in alphabetical order. I am using WP\_Query:
```
<?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
```
),
Any ideas? | `meta_query` and `orderby` are seperate parameters, you just put them together in an array. You will have to do one then the other.
e.g.
```
<?php
$args = array(
'post_type' => 'property',
'meta_query' => array(
array(
'relation' => 'AND',
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
'street_clause' => array(
'key' => 'street_name',
'compare' => 'EXISTS',
),
)
)
'orderby' => array(
'city_clause' => 'desc',
'street_clause' => 'desc',
)
)
?>
```
<https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters> |
249,900 | <p>I'm having issues with a query. I want to get the images attached to an individual post of the type <em>rental</em>.</p>
<p>My query is broken as it outputs all the images on the entire site:</p>
<pre><code>$image_query = new WP_Query(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_parent' => $rental->post->ID,
'order' => 'DESC'
)
);
if( $image_query->have_posts() ){
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
echo '<div class="item">';
echo '<img src="'.$imgurl.'">';
echo '</div>';
}
wp_reset_postdata();
}
</code></pre>
<p>Any ideas on how I can adjust this to only get the images attached to the current post?</p>
| [
{
"answer_id": 249894,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p><code>meta_query</code> and <code>orderby</code> are seperate parameters, you just put them together in an a... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109355/"
] | I'm having issues with a query. I want to get the images attached to an individual post of the type *rental*.
My query is broken as it outputs all the images on the entire site:
```
$image_query = new WP_Query(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_parent' => $rental->post->ID,
'order' => 'DESC'
)
);
if( $image_query->have_posts() ){
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
echo '<div class="item">';
echo '<img src="'.$imgurl.'">';
echo '</div>';
}
wp_reset_postdata();
}
```
Any ideas on how I can adjust this to only get the images attached to the current post? | `meta_query` and `orderby` are seperate parameters, you just put them together in an array. You will have to do one then the other.
e.g.
```
<?php
$args = array(
'post_type' => 'property',
'meta_query' => array(
array(
'relation' => 'AND',
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
'street_clause' => array(
'key' => 'street_name',
'compare' => 'EXISTS',
),
)
)
'orderby' => array(
'city_clause' => 'desc',
'street_clause' => 'desc',
)
)
?>
```
<https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters> |
249,901 | <p>I want to break the loop into sections of posts so I can put content in between that doesn't repeat. Is it possible to end the loop and restart?</p>
<p>My code works for my layout works if there are 10 posts on a page. When I have fewer it breaks because the closing div for .grid is tied in with the 10th post showing. </p>
<p>This shows my layout: 1st post, 2-5 in a grid, a non-post div separating, repeat of post then posts in a grid.
<a href="https://i.stack.imgur.com/LkGmi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LkGmi.png" alt="layout"></a></p>
<pre><code> <?php if ( have_posts() ) :
$count = 0;
while ( have_posts() ) : the_post();
$count++;
if ($count == 1) : ?>
<article class="large"></article>
<?php elseif ($count == 2) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 3) : ?>
<article></article>
<?php elseif ($count == 4) : ?>
<article></article>
<?php elseif ($count == 5) : ?>
<article></article>
</div> <!-- .grid -->
<div id="edit">
</div> <!-- #edit -->
<?php elseif ($count == 6) : ?>
<article class="large"></article>
<?php elseif ($count == 7) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 8) : ?>
<article></article>
<?php elseif ($count == 9) : ?>
<article></article>
<?php elseif ($count == 10) : ?>
<article></article>
</div> <!-- .grid -->
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 249906,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": -1,
"selected": false,
"text": "<p>You can use before the <code>while</code> loop</p>\n\n<pre><code>global $wp_query;\n$total_posts = $wp_query-... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78026/"
] | I want to break the loop into sections of posts so I can put content in between that doesn't repeat. Is it possible to end the loop and restart?
My code works for my layout works if there are 10 posts on a page. When I have fewer it breaks because the closing div for .grid is tied in with the 10th post showing.
This shows my layout: 1st post, 2-5 in a grid, a non-post div separating, repeat of post then posts in a grid.
[](https://i.stack.imgur.com/LkGmi.png)
```
<?php if ( have_posts() ) :
$count = 0;
while ( have_posts() ) : the_post();
$count++;
if ($count == 1) : ?>
<article class="large"></article>
<?php elseif ($count == 2) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 3) : ?>
<article></article>
<?php elseif ($count == 4) : ?>
<article></article>
<?php elseif ($count == 5) : ?>
<article></article>
</div> <!-- .grid -->
<div id="edit">
</div> <!-- #edit -->
<?php elseif ($count == 6) : ?>
<article class="large"></article>
<?php elseif ($count == 7) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 8) : ?>
<article></article>
<?php elseif ($count == 9) : ?>
<article></article>
<?php elseif ($count == 10) : ?>
<article></article>
</div> <!-- .grid -->
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
``` | This pattern can be reduced to two main sections, large box and grid boxes.
And you said you were having trouble closing the grid boxes when your posts are less than 10, an easy way to close off the grid would be to check if the current post is equal to the total posts.
Here is my interpretation of your loop:
```
<?php
if (have_posts()) :
while (have_posts()) :
the_post();
$total_posts = $wp_query->post_count;
$current_post = $wp_query->current_post;
// Large boxes
if (in_array($current_post, array(1, 6))) : ?>
<article class="large"></article>
<?php
elseif ($current_post > 1 && $current_post < 6 || $current_post > 6) :
// Open grid box
in_array($current_post, array(2, 7)) ? "<div class='grid'>" : "";
?>
<article></article>
<?php
// Close grid box
in_array($current_post, array(6, $total_posts)) ? "</div> <!-- .grid -->" : "";
// Add seperator
$current_post == 6 ? "<div id='edit'></div> <!-- #edit -->" : "";
endif;
endwhile;
endif;
?>
``` |
249,918 | <p>I am using wordpress 4.6.</p>
<p>I have template register form with page URL <code>domain-name/account/?action=register</code></p>
<p>I want to redirect it to home page after register but instead of that it show </p>
<p>message "You have logged in. You better go to Home" with page URL </p>
<pre><code>domain-name/account/?result=registered.
</code></pre>
<p>I already try below code in theme functions.php</p>
<pre><code>function __my_registration_redirect(){
wp_redirect( '/my-account' );
exit;
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
</code></pre>
<p>but nothing happens</p>
| [
{
"answer_id": 249923,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of your code why don't you try which in the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249918",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109080/"
] | I am using wordpress 4.6.
I have template register form with page URL `domain-name/account/?action=register`
I want to redirect it to home page after register but instead of that it show
message "You have logged in. You better go to Home" with page URL
```
domain-name/account/?result=registered.
```
I already try below code in theme functions.php
```
function __my_registration_redirect(){
wp_redirect( '/my-account' );
exit;
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
```
but nothing happens | Instead of your code why don't you try which in the [codex example](https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_redirect).
This simple example will redirect a user to the `home_url()` upon successful registration.
```
add_filter( 'registration_redirect', 'my_redirect_home' );
function my_redirect_home( $registration_redirect ) {
return home_url();
}
``` |
249,929 | <p>please give me advice Im very new to ajax, I have a list of posts, if I click it will display the posts information in a div without load the page. I know I must use ajax, so I create a file: loadcontent.php in a root folder and use this code below, but I don't know how to send and get data throught ajax. I need to pass an id in order to get post infos.</p>
<pre><code><script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$("#post-container").load("/loadcontent.php");
return false;
});
});
</script>
</code></pre>
| [
{
"answer_id": 249932,
"author": "Kaeles",
"author_id": 109375,
"author_profile": "https://wordpress.stackexchange.com/users/109375",
"pm_score": 4,
"selected": true,
"text": "<p>Use Ajax API provided by WordPress.</p>\n\n<p>In first time, fix your Ajax request :</p>\n\n<pre><code><sc... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103681/"
] | please give me advice Im very new to ajax, I have a list of posts, if I click it will display the posts information in a div without load the page. I know I must use ajax, so I create a file: loadcontent.php in a root folder and use this code below, but I don't know how to send and get data throught ajax. I need to pass an id in order to get post infos.
```
<script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$("#post-container").load("/loadcontent.php");
return false;
});
});
</script>
``` | Use Ajax API provided by WordPress.
In first time, fix your Ajax request :
```
<script>
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$.ajax({
url: myapiurl.ajax_url,
type: 'post|get|put',
data: {
action: 'my_php_function_name',
post_id: post_id
},
success: function(data) {
// What I have to do...
},
fail: {
// What I have to do...
}
});
return false;
});
</script>
```
Now, you have to create your WordPress treatment. You can put this code in your functions.php or in a plugin file.
```
add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );
function my_ajax_scripts() {
wp_localize_script( 'ajaxRequestId', 'myapiurl', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
```
And then... your function that retrieve your posts
```
function my_php_function_name() {
// What I have to do...
}
```
PS: Never put code in root install folder. Use functions.php of your theme, or create plugin. It's very important for maintainability and security. Have fun :) |
249,931 | <p>I want to include a file only in single post page. I've following code but not working;</p>
<pre><code>if (is_single()){
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
</code></pre>
<p>I mean i just want to load lazy-load in only single post page. but above code is not working. Any idea? Hope to get a solve for this problem.</p>
| [
{
"answer_id": 249941,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>The best way would be to create a child theme then duplicate your <code>single.php</code> template file and edi... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109374/"
] | I want to include a file only in single post page. I've following code but not working;
```
if (is_single()){
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
```
I mean i just want to load lazy-load in only single post page. but above code is not working. Any idea? Hope to get a solve for this problem. | [is\_single](https://developer.wordpress.org/reference/functions/is_single/) function checks for $wp\_query global variable is loading single post of any post type or not , $wp\_query is set after running query\_posts function that loaded after [wp](https://codex.wordpress.org/Plugin_API/Action_Reference/wp) action hook.
So you should call this function in the right order ( hook )
```
add_action( 'wp', 'include_single_lazy_load' );
function include_single_lazy_load() {
if( is_single() ) {
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
}
``` |
249,933 | <p>I recently stumbled upon this and was wondering if calling <code>wp_mail()</code> in a theme is allowed or not as per WordPress standards. I should clarify that I'm not overriding it as a pluggable function in the theme, I am just calling it if it exists.</p>
<p>I'm asking here because I've been searching for this but did not find any clear answer stating anything like this.</p>
| [
{
"answer_id": 249941,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>The best way would be to create a child theme then duplicate your <code>single.php</code> template file and edi... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97347/"
] | I recently stumbled upon this and was wondering if calling `wp_mail()` in a theme is allowed or not as per WordPress standards. I should clarify that I'm not overriding it as a pluggable function in the theme, I am just calling it if it exists.
I'm asking here because I've been searching for this but did not find any clear answer stating anything like this. | [is\_single](https://developer.wordpress.org/reference/functions/is_single/) function checks for $wp\_query global variable is loading single post of any post type or not , $wp\_query is set after running query\_posts function that loaded after [wp](https://codex.wordpress.org/Plugin_API/Action_Reference/wp) action hook.
So you should call this function in the right order ( hook )
```
add_action( 'wp', 'include_single_lazy_load' );
function include_single_lazy_load() {
if( is_single() ) {
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
}
``` |
249,948 | <p>My post template won't load the stylesheet, what's going wrong?</p>
<pre><code>function wpse_enqueue_post_template_styles() {
if ( is_post_template( 'category-bedrijven.php' ) ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
</code></pre>
| [
{
"answer_id": 249951,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it like-</p>\n\n<pre><code>function wpse_enqueue_post_template_styles() {\n if ( is_category... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249948",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109390/"
] | My post template won't load the stylesheet, what's going wrong?
```
function wpse_enqueue_post_template_styles() {
if ( is_post_template( 'category-bedrijven.php' ) ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
``` | You can do it like-
```
function wpse_enqueue_post_template_styles() {
if ( is_category('bedrijven') ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
```
Here ***bedrijven*** is your category slug.
As you said the above method hasn't worked for you, so here I'm suggesting another method-
First remove the first method's full code. Then follow this below method step by step-
**Step 1:**
In your theme's `functions.php` put the below code block-
```
function the_dramatist_register_category_styles() {
wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
add_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );
```
By this above code block we are registering your stylesheet file at ***WordPress***. So we can call it anytime.
**Step 2:**
Now go to your `category-bedrijven.php` file and inside this file put the below code-
```
<?php wp_enqueue_style('post-template'); ?>
```
It'll must work if you do it right.
Hope that helps. |
249,961 | <p>I am experiencing a really weird issue. </p>
<p>The built in function the_excerpt() as soon as the user inserts a custom excerpt form the back end return the excerpt which is produced dynamically by WP without a read more button. If the user does not insert a custom excerpt, the function returns the excerpt along with a read more button.</p>
<p>I want to have full control of this function. I used the code</p>
<pre><code>if (!function_exists('sociality_excerpt_more')) {
function sociality_excerpt_more($more) {
return $more . '&nbsp<a class="read-more p-color" rel="bookmark" title="'. get_the_title() .'" href="'. get_permalink($post->ID) . '">'. esc_html__('View more','g5plus-handmade') .'<i class="pe-7s-right-arrow"></i></a>';
}
add_filter('the_excerpt', 'sociality_excerpt_more');
}
</code></pre>
<p>but it does not have an effect. Using this snippet the function returns twice a read more button if the user does not insert a custom excerpt.</p>
<p>Any help appreciated :)</p>
| [
{
"answer_id": 249951,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it like-</p>\n\n<pre><code>function wpse_enqueue_post_template_styles() {\n if ( is_category... | 2016/12/21 | [
"https://wordpress.stackexchange.com/questions/249961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109321/"
] | I am experiencing a really weird issue.
The built in function the\_excerpt() as soon as the user inserts a custom excerpt form the back end return the excerpt which is produced dynamically by WP without a read more button. If the user does not insert a custom excerpt, the function returns the excerpt along with a read more button.
I want to have full control of this function. I used the code
```
if (!function_exists('sociality_excerpt_more')) {
function sociality_excerpt_more($more) {
return $more . ' <a class="read-more p-color" rel="bookmark" title="'. get_the_title() .'" href="'. get_permalink($post->ID) . '">'. esc_html__('View more','g5plus-handmade') .'<i class="pe-7s-right-arrow"></i></a>';
}
add_filter('the_excerpt', 'sociality_excerpt_more');
}
```
but it does not have an effect. Using this snippet the function returns twice a read more button if the user does not insert a custom excerpt.
Any help appreciated :) | You can do it like-
```
function wpse_enqueue_post_template_styles() {
if ( is_category('bedrijven') ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
```
Here ***bedrijven*** is your category slug.
As you said the above method hasn't worked for you, so here I'm suggesting another method-
First remove the first method's full code. Then follow this below method step by step-
**Step 1:**
In your theme's `functions.php` put the below code block-
```
function the_dramatist_register_category_styles() {
wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
add_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );
```
By this above code block we are registering your stylesheet file at ***WordPress***. So we can call it anytime.
**Step 2:**
Now go to your `category-bedrijven.php` file and inside this file put the below code-
```
<?php wp_enqueue_style('post-template'); ?>
```
It'll must work if you do it right.
Hope that helps. |
250,032 | <p>I'm wondering how to get at custom field information attached to a page, not a post.</p>
<p>Using get_post_meta seems like the right idea, but I don't know how to tell the function to look at page ids and not post ids. Also it's no clear to me if this function can work outside the loop.</p>
<p>A short piece of code showing how to access the page custom field would be really useful. </p>
| [
{
"answer_id": 250034,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": true,
"text": "<p>Sometimes WordPress is criticized treating everything as a <code>post</code>. The matter of fact is, po... | 2016/12/22 | [
"https://wordpress.stackexchange.com/questions/250032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109442/"
] | I'm wondering how to get at custom field information attached to a page, not a post.
Using get\_post\_meta seems like the right idea, but I don't know how to tell the function to look at page ids and not post ids. Also it's no clear to me if this function can work outside the loop.
A short piece of code showing how to access the page custom field would be really useful. | Sometimes WordPress is criticized treating everything as a `post`. The matter of fact is, post type `pages`, post type `post` - both are actually Post in database. So no post will collide with any page ID. :)
So simply a `get_post_meta()` is enough.
But if you still want something specific to Pages, you can use:
```
if( is_page() ) get_post_meta(...);
```
Yes, you can use `get_post_meta()` outside the loop. But instead of passing the post\_id using `get_the_ID()` you have to pass the post\_id manually. |
250,041 | <p>I have created a a site on my localhost, But Now I need to upload website on live server so i need to export word press DB from Phpmyadmin, But I cant find any WP DB there.</p>
<p>Here is my <strong>wp-config file</strong></p>
<pre><code>/** The name of the database for WordPress */
define('DB_NAME', 'bitnami_wordpress');
/** MySQL database username */
define('DB_USER', 'bn_wordpress');
/** MySQL database password */
define('DB_PASSWORD', '0cca6aaab5');
/** MySQL hostname */
define('DB_HOST', 'localhost:3306');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
</code></pre>
<p><strong>phpmyadmin config file</strong></p>
<pre><code>/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '123456';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
</code></pre>
<p><strong>Here is my phpmyadmin screenshot</strong> </p>
<p><a href="https://i.stack.imgur.com/EvfLb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EvfLb.png" alt="enter image description here"></a></p>
<p>I have logged in my phpmyadmin through root user, so i have all the privileges (in case)</p>
<p>Can anyone tell me what's the issue here ??</p>
| [
{
"answer_id": 250043,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin named 'adminer'. You can use that.</p>\n\n<p>And my all time favourite for moving wordpress... | 2016/12/22 | [
"https://wordpress.stackexchange.com/questions/250041",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101083/"
] | I have created a a site on my localhost, But Now I need to upload website on live server so i need to export word press DB from Phpmyadmin, But I cant find any WP DB there.
Here is my **wp-config file**
```
/** The name of the database for WordPress */
define('DB_NAME', 'bitnami_wordpress');
/** MySQL database username */
define('DB_USER', 'bn_wordpress');
/** MySQL database password */
define('DB_PASSWORD', '0cca6aaab5');
/** MySQL hostname */
define('DB_HOST', 'localhost:3306');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
```
**phpmyadmin config file**
```
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '123456';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
```
**Here is my phpmyadmin screenshot**
[](https://i.stack.imgur.com/EvfLb.png)
I have logged in my phpmyadmin through root user, so i have all the privileges (in case)
Can anyone tell me what's the issue here ?? | I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation?
```
user: bn_wordpress
pass: 0cca6aaab5
port: 3306
```
We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:
```
mysqldump -u [uname] -p[pass] db_name > db_backup.sql
```
A simpler \*(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.
I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you. |
250,051 | <p>I have a query that works when I have a field view_type = sale but when the view_type = lead it doesn't return any records even when I know there is one. Here is the query...</p>
<pre><code> SELECT a.id, a.user_email, a.user_registered, a.user_login, b1.meta_value AS first_name, b2.meta_value as last_name, b3.meta_value as qualified,
b4.meta_value as referrer,
b5.meta_value as view_type,
b6.meta_value as ref_by,
b7.meta_value as wp_optimizemember_custom_fields
FROM wp_users a
INNER JOIN wp_usermeta b1 ON b1.user_id = a.ID AND b1.meta_key = 'first_name'
INNER JOIN wp_usermeta b2 ON b2.user_id = a.ID AND b2.meta_key = 'last_name'
INNER JOIN wp_usermeta b3 ON b3.user_id = a.ID AND b3.meta_key = 'qualified'
INNER JOIN wp_usermeta b4 ON b4.user_id = a.ID AND b4.meta_key = 'referrer'
INNER JOIN wp_usermeta b5 ON b5.user_id = a.ID AND b5.meta_key = 'view_type'
INNER JOIN wp_usermeta b6 ON b6.user_id = a.ID AND b6.meta_key = 'ref_by'
INNER JOIN wp_usermeta b7 ON b7.user_id = a.ID AND b7.meta_key = 'wp_optimizemember_custom_fields'
WHERE (b4.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead') or
(b6.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead')
</code></pre>
<p>What wrong with this query?</p>
| [
{
"answer_id": 250043,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin named 'adminer'. You can use that.</p>\n\n<p>And my all time favourite for moving wordpress... | 2016/12/22 | [
"https://wordpress.stackexchange.com/questions/250051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88860/"
] | I have a query that works when I have a field view\_type = sale but when the view\_type = lead it doesn't return any records even when I know there is one. Here is the query...
```
SELECT a.id, a.user_email, a.user_registered, a.user_login, b1.meta_value AS first_name, b2.meta_value as last_name, b3.meta_value as qualified,
b4.meta_value as referrer,
b5.meta_value as view_type,
b6.meta_value as ref_by,
b7.meta_value as wp_optimizemember_custom_fields
FROM wp_users a
INNER JOIN wp_usermeta b1 ON b1.user_id = a.ID AND b1.meta_key = 'first_name'
INNER JOIN wp_usermeta b2 ON b2.user_id = a.ID AND b2.meta_key = 'last_name'
INNER JOIN wp_usermeta b3 ON b3.user_id = a.ID AND b3.meta_key = 'qualified'
INNER JOIN wp_usermeta b4 ON b4.user_id = a.ID AND b4.meta_key = 'referrer'
INNER JOIN wp_usermeta b5 ON b5.user_id = a.ID AND b5.meta_key = 'view_type'
INNER JOIN wp_usermeta b6 ON b6.user_id = a.ID AND b6.meta_key = 'ref_by'
INNER JOIN wp_usermeta b7 ON b7.user_id = a.ID AND b7.meta_key = 'wp_optimizemember_custom_fields'
WHERE (b4.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead') or
(b6.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead')
```
What wrong with this query? | I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation?
```
user: bn_wordpress
pass: 0cca6aaab5
port: 3306
```
We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:
```
mysqldump -u [uname] -p[pass] db_name > db_backup.sql
```
A simpler \*(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.
I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you. |
250,076 | <p><a href="https://stackoverflow.com/questions/4915753/how-can-i-remove-3-characters-at-the-end-of-a-string-in-php">This snippet</a> shows us how to remove 3 characters at the end of a string...</p>
<pre><code>echo substr($string, 0, -3);
</code></pre>
<p>I'd like to find a way to use a custom field value as the string. This is what I've tried with no luck...</p>
<pre><code>echo substr( get_post_meta( $post->ID, "CUSTOMFIELD", true ), 0, -3 );
</code></pre>
| [
{
"answer_id": 250078,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": true,
"text": "<p>You have to consider that you're dealing with <a href=\"http://php.net/manual/en/function.substr.php... | 2016/12/22 | [
"https://wordpress.stackexchange.com/questions/250076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | [This snippet](https://stackoverflow.com/questions/4915753/how-can-i-remove-3-characters-at-the-end-of-a-string-in-php) shows us how to remove 3 characters at the end of a string...
```
echo substr($string, 0, -3);
```
I'd like to find a way to use a custom field value as the string. This is what I've tried with no luck...
```
echo substr( get_post_meta( $post->ID, "CUSTOMFIELD", true ), 0, -3 );
``` | You have to consider that you're dealing with [`substr()`](http://php.net/manual/en/function.substr.php) a *string* related function as the **str** in the function name indicates. That does mean that the parameter `$string` you give actually has to be of the [type `string`](http://php.net/manual/en/language.types.intro.php).
[`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/) on the other hand does just give you back whatever type you saved in the first place. So it isn't guaranteed that your getting back a string - you have to make sure of that yourself. Which you can do by [type casting](http://php.net/manual/en/language.types.type-juggling.php) the value, variable you receive.
So far so good, let's put it together:
```
$custom_field = (string) get_post_meta( $post->ID, "CUSTOMFIELD", true );
echo substr( $custom_field, 0, -3 );
``` |
250,102 | <p>I've mistakenly deleted the <strong><code>functions.php</code></strong> file of my Twenty Sixteen WordPress Theme running the command below:</p>
<pre><code>rm /var/www/html/wp/wp-content/themes/twentysixteen/functions.php
</code></pre>
<p>The Twenty Sixteen Theme is my currently active theme and as such, my WordPress site is no longer accessible as it used to be <em>(ref. screenshot below)</em>.</p>
<p><a href="https://i.stack.imgur.com/Ei2ur.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ei2ur.png" alt="enter image description here"></a></p>
<p>How do I fix it?</p>
| [
{
"answer_id": 250108,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You can always re-download the Twenty Sixteen theme from the official <a href=\"https://wordpress.org/themes/tw... | 2016/12/22 | [
"https://wordpress.stackexchange.com/questions/250102",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70405/"
] | I've mistakenly deleted the **`functions.php`** file of my Twenty Sixteen WordPress Theme running the command below:
```
rm /var/www/html/wp/wp-content/themes/twentysixteen/functions.php
```
The Twenty Sixteen Theme is my currently active theme and as such, my WordPress site is no longer accessible as it used to be *(ref. screenshot below)*.
[](https://i.stack.imgur.com/Ei2ur.png)
How do I fix it? | To fix your site, you should get another [**`functions.php`**](https://github.com/WordPress/twentysixteen/blob/master/functions.php).
As such, you can get that from your most recent and operational backup and upload it unto the location of the mistakenly deleted one.
In case you don't have a backup, your last option will be to download a fresh copy of your [theme](https://downloads.wordpress.org/theme/twentysixteen.1.3.zip "Download the Twenty Sixteen WordPress Theme"); once that done, extract and upload the **`functions.php`** file it contains unto the location of the one you've mistakenly deleted from your server.
In the later case (should you have edited directly your **`functions.php`** - *which is not a recommended practice*), you cannot recover any previous modifications performed on the file.
*Should you consider editing the Twenty Sixteen WordPress Theme or any other one from the [WordPress Repository](https://wordpress.org/themes/) or any other source, I will recommend you create a [Child Theme](https://codex.wordpress.org/Child_Themes "Get started with WordPress Child Themes") of the theme you intended to use for that purpose, rather than editing the actual theme directly.* |
250,147 | <p>I need your help.</p>
<p>There is my problem: I have custom post type "Player". And this <em>CPT</em> has custom field "Seasons". Seasons can have multiple values separated by comma - for example "2014,2015,2016" etc.</p>
<p>Now I need filter list of player who played in certain seasons - for example 2015 and 2016.</p>
<p>And now I need your help with this <code>wp_query</code>. I try this code, but it do not work :-/</p>
<pre><code>query_posts(
array(
'post_type' => 'player',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( '2015','2016'),
'compare' => 'IN',
),
),
)
);
</code></pre>
<p>Please help.</p>
<p>Thanks, <br>
libor</p>
| [
{
"answer_id": 250182,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I would do it with <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63734/"
] | I need your help.
There is my problem: I have custom post type "Player". And this *CPT* has custom field "Seasons". Seasons can have multiple values separated by comma - for example "2014,2015,2016" etc.
Now I need filter list of player who played in certain seasons - for example 2015 and 2016.
And now I need your help with this `wp_query`. I try this code, but it do not work :-/
```
query_posts(
array(
'post_type' => 'player',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( '2015','2016'),
'compare' => 'IN',
),
),
)
);
```
Please help.
Thanks,
libor | Expanding a bit on the answer from @dgarceran
Generally, using the `WP_Query` class is probably a good idea for querying posts.
We'll want to pass arguments to that query.
In your case we'll likely want use one of the following:
1. "**Custom Field Parameters**" - `meta_query`
2. "**Taxonomy Parameters**" - `tax_query`
For a nearly comprehensive example of all the options I like to reference this gist: <https://gist.github.com/luetkemj/2023628>.
Also see the Codex: <https://codex.wordpress.org/Class_Reference/WP_Query>
Both take an array of associative arrays e.g.
**Note**: I'll be using syntax that is compatible with as of PHP 5.4
```
$meta_query_args = [
[
'key' => 'season',
'value' => [ '2015', '2016' ],
'compare' => 'IN',
],
];
```
We can bring those arguments into our instance of `WP_Query`
```
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'meta_query' => $meta_query_args,
];
$the_query = new WP_Query( $args );
```
What's happenning at this point is WordPress is going to check all posts that match your **custom post type** `player`. Then, it will query the metadata you've set with key `season`. Any posts matching `2015` or `2016` will be returned.
**Note:** using `meta_query` this way isn't generally recommended because it's a little heavy on the database. The consensus seems to be that querying taxonomies is more performant (don't quote me on that, couldn't find my source)
So for a quick alternative, I reccomend the following example:
```
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
```
Now we can actually loop through the data, here's some example markup:
```
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
```
When you use `WP_Query` especially in templates, make sure you end with `wp_reset_postdata();`
Putting it altogether (tl;dr)
```
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
?>
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
<?php
wp_reset_postdata();
```
**Front-end view of our query:**
[](https://i.stack.imgur.com/o5Cr8.png)
**Dashboard view of CPT Player posts:**
[](https://i.stack.imgur.com/k74ej.png)
Hope that provides a bit of context |
250,150 | <p>I've got an array of images attached to a post, and can output them sequentually just fine:</p>
<p>1 2 3 4 5 6 7</p>
<p>How can I get three images at a time from the array, then step one image forward to create the following arrays of three images:</p>
<p>1 2 3</p>
<p>2 3 4</p>
<p>3 4 5</p>
<p>4 5 6</p>
<p>and so on?</p>
<p>Here's my code:</p>
<pre><code>global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
if ($images) :
$i = 0;
foreach ($images as $attachment_id => $image) :
$i++;
$img_url = wp_get_attachment_url( $image->ID );
?>
<div class="item <?php if($i == 1){echo ' active';} ?> class="<?php echo $i; ?>"">
<img src="<?php echo $img_url; ?>" title="<?php echo $i; ?>" />
</div>
<?php endforeach; ?>
<?php endif;
</code></pre>
| [
{
"answer_id": 250158,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 3,
"selected": true,
"text": "<p>You can split your array using the following</p>\n\n<pre><code>$array = array(1,2,3,4,5,6);\n$number_of_elements... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109355/"
] | I've got an array of images attached to a post, and can output them sequentually just fine:
1 2 3 4 5 6 7
How can I get three images at a time from the array, then step one image forward to create the following arrays of three images:
1 2 3
2 3 4
3 4 5
4 5 6
and so on?
Here's my code:
```
global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
if ($images) :
$i = 0;
foreach ($images as $attachment_id => $image) :
$i++;
$img_url = wp_get_attachment_url( $image->ID );
?>
<div class="item <?php if($i == 1){echo ' active';} ?> class="<?php echo $i; ?>"">
<img src="<?php echo $img_url; ?>" title="<?php echo $i; ?>" />
</div>
<?php endforeach; ?>
<?php endif;
``` | You can split your array using the following
```
$array = array(1,2,3,4,5,6);
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
print_r( $split );
``` |
250,164 | <p>I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)</p>
<pre><code>$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC LIMIT ${offset}, ${items_per_page}" );
</code></pre>
| [
{
"answer_id": 250158,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 3,
"selected": true,
"text": "<p>You can split your array using the following</p>\n\n<pre><code>$array = array(1,2,3,4,5,6);\n$number_of_elements... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88860/"
] | I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)
```
$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC LIMIT ${offset}, ${items_per_page}" );
``` | You can split your array using the following
```
$array = array(1,2,3,4,5,6);
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
print_r( $split );
``` |
250,167 | <p>I am trying to update the value of one custom post type's meta when another custom post type is deleted.</p>
<p>When a space_rental is deleted, I need to update some meta value on a space.</p>
<p>I don't think I can use <code>delete_post</code> because it fires after the meta data has been deleted, but this isn't working for me either (either on trashing the post or emptying the trash).</p>
<p>Here is the function and below that is the structure of the meta data for each post type.</p>
<pre><code>//When a space_rental is deleted, we release the space slots they had saved
add_action( 'before_delete_post', 'tps_delete_space_rental' );
function tps_delete_space_rental( $postid ){
if (get_post_type($postid) != 'space_rental') {
return;
}
//Loop through the selected slots in the rental
$selectedSlots = get_post_meta($postid, 'selectedSlots', true);
foreach ($selectedSlots as $slot) {
$spaceSlots = get_post_meta($slot['spaceid'], 'allSlots', true);
//Loop through the slots in the space and find the ones that have the rentalID set to the deleted post
foreach ($spaceSlots as $sSlot) {
if($postid == $sSlot['details']['rentalID']) {
$sSlot['details']['slotStatus'] = 'open';
}
}
}
}
</code></pre>
<p>The 'space' post_type meta is stored like this:</p>
<pre><code>allSlots => array(
'timestamp' => '123456789', //timestamp representing this slot
'details' => array(
'slotStatus' => 'open', //this is either open or filled
'slotUser' => 123, //The ID of the user who owns the rental using this slot
'rentalID' => 345, //The post_id of the 'space_rental' that is using this slot
),
);
</code></pre>
<p>This 'space_rental' post_type meta is stored like this:</p>
<pre><code>selectedSlots => array(
'spaceSlots' => array(
123456789, 654321987, 9876432654, etc...,// An array of timestamps in this rental
),
'spaceid' => 789, //The post_id of the 'space' where this rental is
);
</code></pre>
| [
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow norefer... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] | I am trying to update the value of one custom post type's meta when another custom post type is deleted.
When a space\_rental is deleted, I need to update some meta value on a space.
I don't think I can use `delete_post` because it fires after the meta data has been deleted, but this isn't working for me either (either on trashing the post or emptying the trash).
Here is the function and below that is the structure of the meta data for each post type.
```
//When a space_rental is deleted, we release the space slots they had saved
add_action( 'before_delete_post', 'tps_delete_space_rental' );
function tps_delete_space_rental( $postid ){
if (get_post_type($postid) != 'space_rental') {
return;
}
//Loop through the selected slots in the rental
$selectedSlots = get_post_meta($postid, 'selectedSlots', true);
foreach ($selectedSlots as $slot) {
$spaceSlots = get_post_meta($slot['spaceid'], 'allSlots', true);
//Loop through the slots in the space and find the ones that have the rentalID set to the deleted post
foreach ($spaceSlots as $sSlot) {
if($postid == $sSlot['details']['rentalID']) {
$sSlot['details']['slotStatus'] = 'open';
}
}
}
}
```
The 'space' post\_type meta is stored like this:
```
allSlots => array(
'timestamp' => '123456789', //timestamp representing this slot
'details' => array(
'slotStatus' => 'open', //this is either open or filled
'slotUser' => 123, //The ID of the user who owns the rental using this slot
'rentalID' => 345, //The post_id of the 'space_rental' that is using this slot
),
);
```
This 'space\_rental' post\_type meta is stored like this:
```
selectedSlots => array(
'spaceSlots' => array(
123456789, 654321987, 9876432654, etc...,// An array of timestamps in this rental
),
'spaceid' => 789, //The post_id of the 'space' where this rental is
);
``` | There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
``` |
250,191 | <p>I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". Iam trying the below code but it doesn't work.</p>
<pre><code><script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
</code></pre>
<p>My logout code is below:</p>
<pre><code>if ( is_user_logged_in() ) {
$data .= '<li><a class="add-new" href="'. wp_logout_url() .'" class="btn btn-primary" >'.$this->icon_sign_out.' Logout</a></li>';
}
</code></pre>
<p>Can the below code works or not?</p>
<pre><code>function my_redirect(){
<script>
location.reload();
</script>
exit();
}
add_filter('wp_logout','my_redirect');
</code></pre>
<p>I think this issue totally browser issue not belongs to server. I think just a page refresh that does the trick. I was using 'wp_logout_url' for user logout. how to do it can anyone plz tell me? Thanks in advance.</p>
| [
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow norefer... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250191",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] | I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". Iam trying the below code but it doesn't work.
```
<script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
```
My logout code is below:
```
if ( is_user_logged_in() ) {
$data .= '<li><a class="add-new" href="'. wp_logout_url() .'" class="btn btn-primary" >'.$this->icon_sign_out.' Logout</a></li>';
}
```
Can the below code works or not?
```
function my_redirect(){
<script>
location.reload();
</script>
exit();
}
add_filter('wp_logout','my_redirect');
```
I think this issue totally browser issue not belongs to server. I think just a page refresh that does the trick. I was using 'wp\_logout\_url' for user logout. how to do it can anyone plz tell me? Thanks in advance. | There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
``` |
250,205 | <p>I'm preparing plugin and I have trouble to call (and return) javascript from each (same) shortcode in one wp page/post. Javascript returns values only to last shortcode in page.</p>
<p>PHP code here:</p>
<pre><code>add_shortcode( 'ada_chart', 'ada_chart_stranka' );
function ada_chart_stranka ($atts) {
$a = shortcode_atts( array(
'cid' => '',
), $atts );
$cislo_chart = $a['cid'];
wp_register_script( 'ada_chart_handle', plugins_url().'/ada-chart/js/ada-chart1.js' );
$ada_sheet_params = array(
'ada_ch_cislo' => $cislo_chart,
);
wp_localize_script( 'ada_chart_handle', 'ada_ch', $ada_sheet_params );
wp_enqueue_script( 'ada_chart_handle');
return 'atribut: '.$cislo_chart;
}
</code></pre>
<p>and JS script here:</p>
<pre><code> var cisloChart = ada_ch.ada_ch_cislo;
document.getElementById('chart_div'+cisloChart).innerHTML = 'Cislo: ' + cisloChart;
</code></pre>
<p>Can anybody hepl me? Thanks</p>
| [
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow norefer... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109514/"
] | I'm preparing plugin and I have trouble to call (and return) javascript from each (same) shortcode in one wp page/post. Javascript returns values only to last shortcode in page.
PHP code here:
```
add_shortcode( 'ada_chart', 'ada_chart_stranka' );
function ada_chart_stranka ($atts) {
$a = shortcode_atts( array(
'cid' => '',
), $atts );
$cislo_chart = $a['cid'];
wp_register_script( 'ada_chart_handle', plugins_url().'/ada-chart/js/ada-chart1.js' );
$ada_sheet_params = array(
'ada_ch_cislo' => $cislo_chart,
);
wp_localize_script( 'ada_chart_handle', 'ada_ch', $ada_sheet_params );
wp_enqueue_script( 'ada_chart_handle');
return 'atribut: '.$cislo_chart;
}
```
and JS script here:
```
var cisloChart = ada_ch.ada_ch_cislo;
document.getElementById('chart_div'+cisloChart).innerHTML = 'Cislo: ' + cisloChart;
```
Can anybody hepl me? Thanks | There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
``` |
250,210 | <p>I'm using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that. </p>
<p>This is the code in my template file:</p>
<pre><code><img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">
</code></pre>
<p>This is the code in my <code>functions.php</code> file to add the custom size:</p>
<pre><code>add_image_size( 'image-thumbnail', 525, 350, true );
</code></pre>
| [
{
"answer_id": 250217,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative b... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] | I'm using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that.
This is the code in my template file:
```
<img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">
```
This is the code in my `functions.php` file to add the custom size:
```
add_image_size( 'image-thumbnail', 525, 350, true );
``` | Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:
```
$img = get_theme_mod('image-1');
if (!empty ($img)) {
$img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
}
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
```
In words. Get the mod. If it exists search `$img` for the occurence of `jpg|jpeg|png|gif` at the end of the string and then prepend it with the image size, eg `...image-525x350.jpg`. If that file does not exist, use the default. If there is no mod, also use the default. |
250,241 | <p>My WordPress (v4.7) site's media settings only shows sizes for Thumbnail, Medium, and Large. How do I add a Small size to it?</p>
| [
{
"answer_id": 250217,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative b... | 2016/12/23 | [
"https://wordpress.stackexchange.com/questions/250241",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51855/"
] | My WordPress (v4.7) site's media settings only shows sizes for Thumbnail, Medium, and Large. How do I add a Small size to it? | Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:
```
$img = get_theme_mod('image-1');
if (!empty ($img)) {
$img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
}
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
```
In words. Get the mod. If it exists search `$img` for the occurence of `jpg|jpeg|png|gif` at the end of the string and then prepend it with the image size, eg `...image-525x350.jpg`. If that file does not exist, use the default. If there is no mod, also use the default. |
250,264 | <p>Every WordPress page can be described as having two titles:</p>
<ol>
<li><p>The page/post title, which is displayed within the page/post via the <code>the_title()</code> function call</p></li>
<li><p>The html <code><title></title></code> tag that displays the title on top of the browser</p></li>
</ol>
<p>I am writing a plugin which at one point should change the title of a page dynamically (well, it should change both titles described above).</p>
<p>So, for step 1 above, I found multiple solutions on Stack Overflow (such as <a href="https://wordpress.stackexchange.com/questions/46707/change-page-title-from-plugin">this</a> or <a href="https://wordpress.stackexchange.com/questions/33101/how-do-i-set-the-page-title-dynamically">this</a>). Those are great for only step 1 above.</p>
<p>For step 2, I found <a href="https://wordpress.stackexchange.com/questions/51479/setting-title-using-wp-title-filter">this</a> solution; in a nutshell, this is how it works:</p>
<pre><code>add_filter('wp_title', 'change_page_title');
function change_page_title ($title) {
// Do some magic, and eventually modify $title then return it
return $title;
}
</code></pre>
<p>But the suggested solution is not working for me; and by not working I mean that the filter is not calling the associated function. I am not sure what the problem is; is it because this filter is being called from within the plugin not the theme? (Just FYI, I do not have access to the theme files, so it has to be done from within the plugin).</p>
<p>How can I accomplish this? How can I change the browser title of a page dynamically from within a plugin? </p>
<p>Thanks.</p>
| [
{
"answer_id": 250266,
"author": "pankaj choudhary",
"author_id": 109569,
"author_profile": "https://wordpress.stackexchange.com/users/109569",
"pm_score": 1,
"selected": false,
"text": "<p>Using this code on you page.php or page which you want to change\n<code><pre>\n<title>... | 2016/12/24 | [
"https://wordpress.stackexchange.com/questions/250264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] | Every WordPress page can be described as having two titles:
1. The page/post title, which is displayed within the page/post via the `the_title()` function call
2. The html `<title></title>` tag that displays the title on top of the browser
I am writing a plugin which at one point should change the title of a page dynamically (well, it should change both titles described above).
So, for step 1 above, I found multiple solutions on Stack Overflow (such as [this](https://wordpress.stackexchange.com/questions/46707/change-page-title-from-plugin) or [this](https://wordpress.stackexchange.com/questions/33101/how-do-i-set-the-page-title-dynamically)). Those are great for only step 1 above.
For step 2, I found [this](https://wordpress.stackexchange.com/questions/51479/setting-title-using-wp-title-filter) solution; in a nutshell, this is how it works:
```
add_filter('wp_title', 'change_page_title');
function change_page_title ($title) {
// Do some magic, and eventually modify $title then return it
return $title;
}
```
But the suggested solution is not working for me; and by not working I mean that the filter is not calling the associated function. I am not sure what the problem is; is it because this filter is being called from within the plugin not the theme? (Just FYI, I do not have access to the theme files, so it has to be done from within the plugin).
How can I accomplish this? How can I change the browser title of a page dynamically from within a plugin?
Thanks. | A post or page has only one title, the title tag `<title>` is the document title.
The filter `wp_title` filters the output of `wp_title()` function, which was used before to output the title of the document. In WordPress 4.1, the title-tag support in themes was introduced and [`wp_get_document_title()`](https://developer.wordpress.org/reference/functions/wp_get_document_title/) is used instead of `wp_title()`. So, if your theme supports `title-tag`, `wp_title` filter has not effect, but you can use a other filters:
[`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/) to set a new title
```
add_filter( 'pre_get_document_title', 'cyb_change_page_title' );
function cyb_change_page_title () {
return "Custom title";
}
```
[`document_title_separator`](https://developer.wordpress.org/reference/hooks/document_title_separator/) to filter the title separator
```
add_filter('document_title_separator', 'cyb_change_document_title_separator');
function cyb_change_document_title_separator ( $sep ) {
return "|";
}
```
[`documente_title_parts`](https://developer.wordpress.org/reference/hooks/document_title_parts/) to filter different parts of the title: title, page number, tagline and site name.
```
add_filter( 'document_title_parts', 'cyb_change_document_title_parts' );
function cyb_change_document_title_parts ( $title_parts ) {
$title_parts['title'] = 'Custom title';
$title_parts['page'] = 54;
$title_parts['tagline'] = "Custom tagline";
$title_parts['site'] = "My Site"; // When not on home page
return $title_parts;
}
```
PD: You can use [`current_theme_supports( 'title-tag' )`](https://developer.wordpress.org/reference/functions/current_theme_supports/) to check if theme supports `title-tag` or not. |
250,280 | <p>Considering regular WordPress ajax requests like these:</p>
<pre><code>add_action( 'wp_ajax_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
add_action( 'wp_ajax_nopriv_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
</code></pre>
<p>Will it be best to end function <code>merrychristmas_happynewyear</code> with <code>die()</code>, <code>die(0)</code>, <code>wp_die()</code>, or something else and why?</p>
| [
{
"answer_id": 250282,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": false,
"text": "<p>From the codex <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\"><strong>AJAX in Plugins</strong></a></p>... | 2016/12/24 | [
"https://wordpress.stackexchange.com/questions/250280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] | Considering regular WordPress ajax requests like these:
```
add_action( 'wp_ajax_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
add_action( 'wp_ajax_nopriv_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
```
Will it be best to end function `merrychristmas_happynewyear` with `die()`, `die(0)`, `wp_die()`, or something else and why? | Using `wp_die()` is the best of those options.
As others have noted, there are many reasons to prefer a WordPress-specific function over the plain `die` or `exit`:
* It allows other plugins to hook into the actions called by `wp_die()`.
* It allows a special handler for exiting to be used based on context (the behavior of `wp_die()` is tailored based on whether the request is an Ajax request or not).
* It makes it possible to test your code.
The last one is more important, which is why [I added that note to the Codex](https://codex.wordpress.org/index.php?title=AJAX_in_Plugins&diff=148870&oldid=148219). If you want to [create unit/integration tests](http://codesymphony.co/wp-ajax-plugin-unit-testing/) for your code, you will not be able to test a function that calls `exit` or `die` directly. It will terminate the script, like it is supposed to. The way that WordPress's own tests are set up to avoid this (for the Ajax callbacks that it has tests for), is to hook into the actions triggered by `wp_die()` and throw an exception. This allows the exception to be caught within the test, and the output of the callback (if any) to be analyzed.
The only time that you would use `die` or `exit` is if you want to bypass any special handling from `wp_die()` and kill the execution immediately. There are some places where WordPress does this (and other places where it might use `die` directly just because the handling from `wp_die()` is not important, or nobody has attempted to create tests for a piece of code yet, so it was overlooked). Remember that this also makes your code more difficult to test, so it would generally only be used in code that isn't in a function body anyway (like WordPress does in `admin-ajax.php`). So if the handling from `wp_die()` is specifically not desired, or you are killing the script at a certain point as a precaution (like `admin-ajax.php` does, expecting that usually an Ajax callback will have already properly exited), then you might consider using `die` directly.
In terms of `wp_die()` vs `wp_die( 0 )`, which you should use depends on what is handling the response of that Ajax request on the front end. If it is expecting a particular response body, then you need to pass that message (or integer, in this case) to `wp_die()`. If all it is listening for is the response being successful (`200` response code or whatever), then there is no need to pass anything to `wp_die()`. I would note, though, that ending with `wp_die( 0 )` would make the response indistinguishable from the default `admin-ajax.php` response. So ending with `0` does not tell you whether your callback was hooked up properly and actually ran. A different message would be better.
As pointed out in other answers, you will often find `wp_send_json()` et al. to be helpful if you are sending a JSON response back, which is generally a good idea. This is also superior to just calling `wp_die()` with a code, because you can pass much more information back in a JSON object, if needed. Using `wp_send_json_success()` and `wp_send_json_error()` will also send the success/error message back in a standard format that any JS Ajax helper functions provided by WordPress will be able to understand (like [`wp.ajax`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/js/wp-util.js?rev=37851#L99)).
**TL;DR:** You should probably always use `wp_die()`, whether in an Ajax callback or not. Even better, send information back with `wp_send_json()` and friends. |
250,288 | <p>can anyone help me </p>
<pre><code>define('FTP_PUBKEY','/home/use/.ssh/id_rsa');
define('FTP_PRIKEY','/home/user/.ssh/id_rsa');
define('FTP_USER','');
define('FTP_PASS','');
define('FTP_HOST','127.0.0.1:22');
</code></pre>
<p>install at located <code>home/user/wordpress</code></p>
<p>keys located at </p>
<p>getting incorrect keys</p>
<p>keys permissons 600, 600 folfer 755</p>
| [
{
"answer_id": 250320,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>For connection through ssh, you have to specify the ssh user using <code>FTP_USER</code></p>\n\n<pre><code>defi... | 2016/12/24 | [
"https://wordpress.stackexchange.com/questions/250288",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109580/"
] | can anyone help me
```
define('FTP_PUBKEY','/home/use/.ssh/id_rsa');
define('FTP_PRIKEY','/home/user/.ssh/id_rsa');
define('FTP_USER','');
define('FTP_PASS','');
define('FTP_HOST','127.0.0.1:22');
```
install at located `home/user/wordpress`
keys located at
getting incorrect keys
keys permissons 600, 600 folfer 755 | For connection through ssh, you have to specify the ssh user using `FTP_USER`
```
define( 'FS_METHOD', 'ssh' );
define( 'FTP_BASE', '/home/user/wordpress' );
define( 'FTP_PUBKEY', '/home/user/.ssh/id_rsa.pub' );
define( 'FTP_PRIKEY', '/home/user/.ssh/id_rsa' );
define( 'FTP_USER', 'user' );
define( 'FTP_HOST', 'localhost:22' );
```
I think you also need to define `FTP_BASE`.
You also need to enable ssh upgrade access. From the Codex:
Enabling SSH Upgrade Access
---------------------------
**There are two ways to upgrade using SSH2.**
The first is to use the [SSH SFTP Updater Support plugin](http://wordpress.org/plugins/ssh-sftp-updater-support/). The second is to use the built-in SSH2 upgrader, which requires the pecl SSH2 extension be installed.
To install the pecl SSH2 extension you will need to issue a command similar to the following or talk to your web hosting provider to get this installed:
```
pecl install ssh2
```
After installing the pecl ssh2 extension you will need to modify your php configuration to automatically load this extension.
pecl is provided by the pear package in most linux distributions. To install pecl in Redhat/Fedora/CentOS:
```
yum -y install php-pear
```
To install pecl in Debian/Ubuntu:
```
apt-get install php-pear
```
It is recommended to use a private key that is not pass-phrase protected. There have been numerous reports that pass phrase protected private keys do not work properly. If you decide to try a pass phrase protected private key you will need to enter the pass phrase for the private key as FTP\_PASS, or entering it in the "Password" field in the presented credential field when installing updates. |
250,304 | <p>Should <code>get_template_directory_uri()</code> be escaped using <code>esc_url()</code>?</p>
<p>I ask because taking an example from the default theme Twenty Fifteen the same function is used in two different places but only in one is it escaped.</p>
<pre><code>wp_enqueue_style( 'twentyfifteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentyfifteen-style' ), '20141010' );
</code></pre>
<p>-</p>
<pre><code><script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
</code></pre>
<p>I would say that that <code>get_template_directory_uri()</code> does not need to be generated as the URL cannot be manipulated externally.</p>
| [
{
"answer_id": 250311,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>In that function we find a hook:</p>\n\n<pre><code>return apply_filters( \n 'template_directory_uri', \n $templa... | 2016/12/24 | [
"https://wordpress.stackexchange.com/questions/250304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17937/"
] | Should `get_template_directory_uri()` be escaped using `esc_url()`?
I ask because taking an example from the default theme Twenty Fifteen the same function is used in two different places but only in one is it escaped.
```
wp_enqueue_style( 'twentyfifteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentyfifteen-style' ), '20141010' );
```
-
```
<script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
```
I would say that that `get_template_directory_uri()` does not need to be generated as the URL cannot be manipulated externally. | In that function we find a hook:
```
return apply_filters(
'template_directory_uri',
$template_dir_uri,
$template,
$theme_root_uri
);
```
So, yes, the URI can be changed by plugins, and you should escape its returned value.
The same principle applies to all WordPress URI functions, like `get_home_url()`, `get_site_url()` and so on. Keep in mind that there are not only good plugin developers out there. Some make mistakes, maybe just very small ones that happen only in some circumstances.
In case of `wp_enqueue_style()`, WordPress **does** escape the URL by default. But that is a wrapper for the **global** `WP_Styles` instance, and this in turn [can be replaced easily](https://wordpress.stackexchange.com/a/108364/73) – even with a less safe version. That's not very likely, but you should be aware of this possibility.
Unfortunately, WP itself doesn't follow the *better safe than sorry* directive. It doesn't even escape translations. My advice is not to look at the core themes for best practices. Always look at the source of the data and see if it can be compromised. |
250,308 | <p>I do have an post/page where the shortcode "question" occurs many times.
What is the best way to get an array of all the "question" shortcodes with their related parms?</p>
<pre><code>[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]
</code></pre>
| [
{
"answer_id": 250312,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": true,
"text": "<pre><code>function wpse250308_get_questions() {\n global $post;\n if ( preg_match_all('/\\[question(.*?)\\]/... | 2016/12/24 | [
"https://wordpress.stackexchange.com/questions/250308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109145/"
] | I do have an post/page where the shortcode "question" occurs many times.
What is the best way to get an array of all the "question" shortcodes with their related parms?
```
[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]
``` | ```
function wpse250308_get_questions() {
global $post;
if ( preg_match_all('/\[question(.*?)\]/', $post->post_content, $questions ) ) {
$questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
// $questions will contain the array of the question shortcodes
//Do your stuff
}
}
```
`$post` isn't available before `wp`. So, you have to hook on it or actions that fires later. |
250,349 | <p>I tried to remove Menus from WordPress customizer (see image)
<a href="https://i.stack.imgur.com/JwOz6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JwOz6.png" alt="enter image description here"></a></p>
<p>I tried the following code on functions.php file and every section was removed except Menus </p>
<pre><code> //Theme customizer
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_section( 'menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register' );
</code></pre>
<p>I even tried </p>
<pre><code>$wp_customize->remove_panel( 'menus');
</code></pre>
<p>but didn't worked i m'i missing something here .appreciate any help on this thanks in advance.</p>
| [
{
"answer_id": 250356,
"author": "mxUser127",
"author_id": 25525,
"author_profile": "https://wordpress.stackexchange.com/users/25525",
"pm_score": -1,
"selected": false,
"text": "<p>Edit files in admin directory on your server. Even though you may find a plugin for this job. This will he... | 2016/12/25 | [
"https://wordpress.stackexchange.com/questions/250349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100679/"
] | I tried to remove Menus from WordPress customizer (see image)
[](https://i.stack.imgur.com/JwOz6.png)
I tried the following code on functions.php file and every section was removed except Menus
```
//Theme customizer
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_section( 'menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register' );
```
I even tried
```
$wp_customize->remove_panel( 'menus');
```
but didn't worked i m'i missing something here .appreciate any help on this thanks in advance. | Try **nav\_menus** instead of **menus** with `remove_panel()`
```
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_panel( 'nav_menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register',50 );
```
Hope this will helps you.
Thank you! |
250,370 | <p>I am building a site using a custom WP theme, and I have been using:</p>
<pre><code><?php include('header-bar.php'); ?>
</code></pre>
<p>in order to include a navigation bar on each page. I intentionally didn't put the navigation in the header.php file because I don't need it on every page.</p>
<p>That bit of code is working fine in certain places, but failing in others.</p>
<p>It works in this scenario:</p>
<pre><code><?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>but it mysteriously fails in this scenario:</p>
<pre><code><?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>In this second scenario, the page displays properly, except for a the 'header-bar.php' code which is nowhere to be found. The change that I am making that seemingly 'breaks' this line of code is by adding the template name. Can anyone offer some insight into why this may be? I'm baffled.</p>
<p>Thanks in advance! CPR</p>
| [
{
"answer_id": 250371,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<p>Hello CandyPaintedRIMS,</p>\n<p>Please try <a href=\"https://developer.wordpress.org/reference... | 2016/12/26 | [
"https://wordpress.stackexchange.com/questions/250370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101243/"
] | I am building a site using a custom WP theme, and I have been using:
```
<?php include('header-bar.php'); ?>
```
in order to include a navigation bar on each page. I intentionally didn't put the navigation in the header.php file because I don't need it on every page.
That bit of code is working fine in certain places, but failing in others.
It works in this scenario:
```
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
```
but it mysteriously fails in this scenario:
```
<?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
```
In this second scenario, the page displays properly, except for a the 'header-bar.php' code which is nowhere to be found. The change that I am making that seemingly 'breaks' this line of code is by adding the template name. Can anyone offer some insight into why this may be? I'm baffled.
Thanks in advance! CPR | Hello CandyPaintedRIMS,
Please try [get\_template\_part()](https://developer.wordpress.org/reference/functions/get_template_part/) function to include any file into your custom template.
**Your code:**
```
<?php include('header-bar.php'); ?>
```
**It should be replaced with:**
```
<?php get_template_part( 'header-bar' ); // include header-bar.php ?>
```
Hope this will helps you.
Thank you |
250,376 | <p>I'm building a phone numbers directory website. Using <code>wp_insert_post()</code> visitors are allowed to add phone numbers without having to register or log in.
There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code:</p>
<p><code>$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}</code></p>
<p>I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not.</p>
<p>If number already exists in database, user shouldn't be allowed to add it.</p>
| [
{
"answer_id": 250380,
"author": "Sofiane Achouba",
"author_id": 92790,
"author_profile": "https://wordpress.stackexchange.com/users/92790",
"pm_score": 1,
"selected": false,
"text": "<p>Hi you can do it like that:</p>\n\n<pre><code>$post_id = wp_insert_post(array (\n 'post_type' ... | 2016/12/26 | [
"https://wordpress.stackexchange.com/questions/250376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105471/"
] | I'm building a phone numbers directory website. Using `wp_insert_post()` visitors are allowed to add phone numbers without having to register or log in.
There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code:
`$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}`
I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not.
If number already exists in database, user shouldn't be allowed to add it. | Try below code.
```
$args = array(
'fields' => 'ids',
'post_type' => 'numbers',
'meta_query' => array(
array(
'key' => 'number',
'value' => $number
)
)
);
$my_query = new WP_Query( $args );
if( empty($my_query->have_posts()) ) {
$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}
}
```
If there is same number in postmeta it will not allow to create post and post meta.
Hope this will helps you. |
250,379 | <p>Im in the midst of customizing WooCommerce checkout, adding a dropdown field which get user's meta keys and show as select option in the checkout page. I also managed to save the selected option after checkout into the order. However, the option is displaying as an integer instead of text in the custom field.</p>
<p>The following codes are my development, I hope someone can guide me out.
<a href="https://i.stack.imgur.com/JIqqP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JIqqP.jpg" alt="dropdown"></a></p>
<p><a href="https://i.stack.imgur.com/789Tg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/789Tg.jpg" alt="Custom Field Value"></a></p>
<p>Retrieving user meta keys and display as dropdown options</p>
<pre><code>add_action('woocommerce_after_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
$user_id = get_current_user_id();
$vessel_one = get_user_meta( $user_id, 'vessel_one', true );
$vessel_two = get_user_meta( $user_id, 'vessel_two', true );
$vessel_three = get_user_meta( $user_id, 'vessel_three', true );
$vessel_four = get_user_meta( $user_id, 'vessel_four', true );
$vessel_five = get_user_meta( $user_id, 'vessel_five', true );
woocommerce_form_field( 'order_vessel', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Select a Vessel' ),
'options' => array( $vessel_one, $vessel_two, $vessel_three, $vessel_four, $vessel_five )
),
$checkout->get_value( 'order_vessel' ));
}
</code></pre>
<p>Save the value into custom field on the order</p>
<pre><code>add_action('woocommerce_checkout_update_order_meta', 'wps_select_checkout_field_update_order_meta');
function wps_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['order_vessel']) update_post_meta( $order_id, 'order_vessel', esc_attr($_POST['order_vessel']));
}
</code></pre>
<p>I hope someone could show me how can I save the value as it is and not converted into an integer. Thank you very much in advance.</p>
| [
{
"answer_id": 250380,
"author": "Sofiane Achouba",
"author_id": 92790,
"author_profile": "https://wordpress.stackexchange.com/users/92790",
"pm_score": 1,
"selected": false,
"text": "<p>Hi you can do it like that:</p>\n\n<pre><code>$post_id = wp_insert_post(array (\n 'post_type' ... | 2016/12/26 | [
"https://wordpress.stackexchange.com/questions/250379",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109645/"
] | Im in the midst of customizing WooCommerce checkout, adding a dropdown field which get user's meta keys and show as select option in the checkout page. I also managed to save the selected option after checkout into the order. However, the option is displaying as an integer instead of text in the custom field.
The following codes are my development, I hope someone can guide me out.
[](https://i.stack.imgur.com/JIqqP.jpg)
[](https://i.stack.imgur.com/789Tg.jpg)
Retrieving user meta keys and display as dropdown options
```
add_action('woocommerce_after_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
$user_id = get_current_user_id();
$vessel_one = get_user_meta( $user_id, 'vessel_one', true );
$vessel_two = get_user_meta( $user_id, 'vessel_two', true );
$vessel_three = get_user_meta( $user_id, 'vessel_three', true );
$vessel_four = get_user_meta( $user_id, 'vessel_four', true );
$vessel_five = get_user_meta( $user_id, 'vessel_five', true );
woocommerce_form_field( 'order_vessel', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Select a Vessel' ),
'options' => array( $vessel_one, $vessel_two, $vessel_three, $vessel_four, $vessel_five )
),
$checkout->get_value( 'order_vessel' ));
}
```
Save the value into custom field on the order
```
add_action('woocommerce_checkout_update_order_meta', 'wps_select_checkout_field_update_order_meta');
function wps_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['order_vessel']) update_post_meta( $order_id, 'order_vessel', esc_attr($_POST['order_vessel']));
}
```
I hope someone could show me how can I save the value as it is and not converted into an integer. Thank you very much in advance. | Try below code.
```
$args = array(
'fields' => 'ids',
'post_type' => 'numbers',
'meta_query' => array(
array(
'key' => 'number',
'value' => $number
)
)
);
$my_query = new WP_Query( $args );
if( empty($my_query->have_posts()) ) {
$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}
}
```
If there is same number in postmeta it will not allow to create post and post meta.
Hope this will helps you. |
250,403 | <p>Looking to discover how to alter my content.php code to add the thumbnail image of the specific posts to my search results located here for example:</p>
<p><a href="https://divesummit.com/?s=suunto&submit=Search" rel="nofollow noreferrer">https://divesummit.com/?s=suunto&submit=Search</a></p>
<p>I would like a thumbnail of the featured post’s image listed along with the smaller blurb of the post in the search results.</p>
<pre><code> <?php get_template_part( 'content', get_post_format() ); ?>
</code></pre>
<p>by somehow changing content.php I can have it include a small thumbnail along with each search result. My theme already has thumb support I just need help implementing it.</p>
<p>Any help on doing this would be appreciated.</p>
<p>PS. I do have a child theme installed</p>
| [
{
"answer_id": 250399,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like server response time and stylesheet loading are causing the greatest delay:</p>\n\n<p><a hre... | 2016/12/26 | [
"https://wordpress.stackexchange.com/questions/250403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109668/"
] | Looking to discover how to alter my content.php code to add the thumbnail image of the specific posts to my search results located here for example:
<https://divesummit.com/?s=suunto&submit=Search>
I would like a thumbnail of the featured post’s image listed along with the smaller blurb of the post in the search results.
```
<?php get_template_part( 'content', get_post_format() ); ?>
```
by somehow changing content.php I can have it include a small thumbnail along with each search result. My theme already has thumb support I just need help implementing it.
Any help on doing this would be appreciated.
PS. I do have a child theme installed | It looks like server response time and stylesheet loading are causing the greatest delay:
[](https://i.stack.imgur.com/z0aag.png)
[](https://i.stack.imgur.com/qam7s.png)
You can measure the network performance of your site yourself using the Network panel in Chrome: Right click > Inspect > Network (refresh the page to load details) |
250,427 | <p>So I'm pretty new at Wordpress development, and I'm a little confused by one thing. After going through and finishing my navigation in my header.php file, I went over to my template for the home page I'm working on. My question is: since the "body" tag is the only place you can write that actually shows up in the browser ("header" tags are for meta data etc), can I have more than one body tag? I read a little into html 5, and it seems there are more tags than just "body" now, but what's the best way to do that? I already have my menus wrapped in and what do I do with the footer, etc? Thanks for any help.</p>
| [
{
"answer_id": 250461,
"author": "Third Essential Designer",
"author_id": 103698,
"author_profile": "https://wordpress.stackexchange.com/users/103698",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/2913303/6887487\">This</a> may help you regarding ha... | 2016/12/27 | [
"https://wordpress.stackexchange.com/questions/250427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] | So I'm pretty new at Wordpress development, and I'm a little confused by one thing. After going through and finishing my navigation in my header.php file, I went over to my template for the home page I'm working on. My question is: since the "body" tag is the only place you can write that actually shows up in the browser ("header" tags are for meta data etc), can I have more than one body tag? I read a little into html 5, and it seems there are more tags than just "body" now, but what's the best way to do that? I already have my menus wrapped in and what do I do with the footer, etc? Thanks for any help. | Structure your theme so you start the `<body>` in the header and you close the `</body>` in the footer (same thing for the `<html>` tag):
header.php
```
<html>
...header content
<body> <!--- body is started in the header, used on every page -->
```
index.php, page.php, single.php, home.php - etc
```
...content
```
footer.php
```
...footer content
</body> <!-- body is closed in the footer, also used on every page -->
</html>
``` |
250,452 | <p>Here is my custom type post code. I want to add the meta box in there...</p>
<pre><code>function events_cust(){
$label = array(
'name' => _x('Events'),
'singular_name' => _x('events'),
'menu_name' => __('Events'),
'add_new' => __('Add Event'),
'add_new_item' => __ ('Add New Event'),
'all_item' => __('All Event'),
'edit_item' => __('Edit Event'),
'new_item' => __('New Event'),
'view_item' => __('View Event'),
'update_item' => __('update Event'),
'search_item' => __('Search Event')
);
$attr = array(
'label' => __('Events'),
'description' => __('Event'),
'labels' => $label,
'supports' => array('title','editor','thumbnail'),
'taxonomies' => array('genres'),
'hiecrarhical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_adim_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('events-lists',$attr);
}
add_action( 'init', 'events_cust', 0 );
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes(){
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists','normal','hight');
}
function show_events_metaboxes(){
echo 'Hello Meta box';
}
</code></pre>
<p>What's wrong with us.</p>
| [
{
"answer_id": 250456,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "<p>Try below code.</p>\n\n<pre><code>add_action('add_meta_boxes','create_events_metaboxes'); \nf... | 2016/12/27 | [
"https://wordpress.stackexchange.com/questions/250452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109713/"
] | Here is my custom type post code. I want to add the meta box in there...
```
function events_cust(){
$label = array(
'name' => _x('Events'),
'singular_name' => _x('events'),
'menu_name' => __('Events'),
'add_new' => __('Add Event'),
'add_new_item' => __ ('Add New Event'),
'all_item' => __('All Event'),
'edit_item' => __('Edit Event'),
'new_item' => __('New Event'),
'view_item' => __('View Event'),
'update_item' => __('update Event'),
'search_item' => __('Search Event')
);
$attr = array(
'label' => __('Events'),
'description' => __('Event'),
'labels' => $label,
'supports' => array('title','editor','thumbnail'),
'taxonomies' => array('genres'),
'hiecrarhical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_adim_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('events-lists',$attr);
}
add_action( 'init', 'events_cust', 0 );
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes(){
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists','normal','hight');
}
function show_events_metaboxes(){
echo 'Hello Meta box';
}
```
What's wrong with us. | Try below code.
```
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes() {
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists');
}
function show_events_metaboxes($post){ echo 'Hello Meta box'; }
```
Hope this will helps you.
Refer from [add\_meta\_box](https://developer.wordpress.org/reference/functions/add_meta_box/) |
250,478 | <p>After installing wordpress importer from Tools option in wordpress, when I try to activate it, it gives fatal error.</p>
<p><img src="https://i.imgur.com/0Ky3XqU.png" alt="Screenshot"></p>
<p>The relevant php code:</p>
<pre><code>class WXR_Parser {
function parse( $file ) {
// Attempt to use proper XML parsers first
if ( extension_loaded( 'simplexml' ) ) {
$parser = new WXR_Parser_SimpleXML;
$result = $parser->parse( $file );
// If SimpleXML succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'SimpleXML_parse_error' != $result->get_error_code() )
return $result;
} else if ( extension_loaded( 'xml' ) ) {
$parser = new WXR_Parser_XML;
$result = $parser->parse( $file );
// If XMLParser succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'XML_parse_error' != $result->get_error_code() )
return $result;
}
// We have a malformed XML file, so display the error and fallthrough to regex
if ( isset($result) && defined('IMPORT_DEBUG') && IMPORT_DEBUG ) {
echo '<pre>';
if ( 'SimpleXML_parse_error' == $result->get_error_code() ) {
foreach ( $result->get_error_data() as $error )
echo $error->line . ':' . $error->column . ' ' . esc_html( $error->message ) . "\n";
} else if ( 'XML_parse_error' == $result->get_error_code() ) {
$error = $result->get_error_data();
echo $error[0] . ':' . $error[1] . ' ' . esc_html( $error[2] );
}
echo '</pre>';
echo '<p><strong>' . __( 'There was an error when reading this WXR file', 'wordpress-importer' ) . '</strong><br />';
echo __( 'Details are shown above. The importer will now try again with a different parser...', 'wordpress-importer' ) . '</p>';
}
// use regular expressions if nothing else available or this is bad XML
$parser = new WXR_Parser_Regex;
return $parser->parse( $file );
}
}
</code></pre>
| [
{
"answer_id": 250480,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 3,
"selected": true,
"text": "<p>That error suggests that the <code>WXR_Parser</code> class is already \"running\" or declared. It's possibl... | 2016/12/27 | [
"https://wordpress.stackexchange.com/questions/250478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106457/"
] | After installing wordpress importer from Tools option in wordpress, when I try to activate it, it gives fatal error.

The relevant php code:
```
class WXR_Parser {
function parse( $file ) {
// Attempt to use proper XML parsers first
if ( extension_loaded( 'simplexml' ) ) {
$parser = new WXR_Parser_SimpleXML;
$result = $parser->parse( $file );
// If SimpleXML succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'SimpleXML_parse_error' != $result->get_error_code() )
return $result;
} else if ( extension_loaded( 'xml' ) ) {
$parser = new WXR_Parser_XML;
$result = $parser->parse( $file );
// If XMLParser succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'XML_parse_error' != $result->get_error_code() )
return $result;
}
// We have a malformed XML file, so display the error and fallthrough to regex
if ( isset($result) && defined('IMPORT_DEBUG') && IMPORT_DEBUG ) {
echo '<pre>';
if ( 'SimpleXML_parse_error' == $result->get_error_code() ) {
foreach ( $result->get_error_data() as $error )
echo $error->line . ':' . $error->column . ' ' . esc_html( $error->message ) . "\n";
} else if ( 'XML_parse_error' == $result->get_error_code() ) {
$error = $result->get_error_data();
echo $error[0] . ':' . $error[1] . ' ' . esc_html( $error[2] );
}
echo '</pre>';
echo '<p><strong>' . __( 'There was an error when reading this WXR file', 'wordpress-importer' ) . '</strong><br />';
echo __( 'Details are shown above. The importer will now try again with a different parser...', 'wordpress-importer' ) . '</p>';
}
// use regular expressions if nothing else available or this is bad XML
$parser = new WXR_Parser_Regex;
return $parser->parse( $file );
}
}
``` | That error suggests that the `WXR_Parser` class is already "running" or declared. It's possible that a theme or another plugin has incorporated that class and did not check if it existed already before initializing. ie. `if ( ! class_exists( 'WXR_Parser' ) )`.
To locate the source of the conflict, deactivate each *theme and plugin* one-by-one. You should be left with just a default theme active (ie. TwentyFifteen). |
250,485 | <p>In order to use HTML5 markup for the comment forms, I add the following code snippet to <code>functions.php</code>:</p>
<pre><code>add_theme_support( 'html5', array( 'comment-form' ) );
</code></pre>
<p>However, it disables client side validation on form submit and I get redirected to an error page:</p>
<p><a href="https://i.stack.imgur.com/78Bpq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/78Bpq.png" alt="Error page redirect"></a></p>
<p>Now, if I remove <code>add_theme_support( 'html5', array( 'comment-form' ) );</code> and submit the comment form, I get client side validation:</p>
<p><a href="https://i.stack.imgur.com/NsH4B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NsH4B.png" alt="Client side validation"></a></p>
<p>Can anybody explain why this is? Is it a bug? Or expected behavior?</p>
<p>I am currently using WordPress 4.7.</p>
| [
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-... | 2016/12/27 | [
"https://wordpress.stackexchange.com/questions/250485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109650/"
] | In order to use HTML5 markup for the comment forms, I add the following code snippet to `functions.php`:
```
add_theme_support( 'html5', array( 'comment-form' ) );
```
However, it disables client side validation on form submit and I get redirected to an error page:
[](https://i.stack.imgur.com/78Bpq.png)
Now, if I remove `add_theme_support( 'html5', array( 'comment-form' ) );` and submit the comment form, I get client side validation:
[](https://i.stack.imgur.com/NsH4B.png)
Can anybody explain why this is? Is it a bug? Or expected behavior?
I am currently using WordPress 4.7. | No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now. |
250,513 | <p>I have a problem. I need to list only 2 roles: customer and shop_manager. 1. How can i do that with this script?</p>
<pre><code>add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
</code></pre>
| [
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-... | 2016/12/27 | [
"https://wordpress.stackexchange.com/questions/250513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109748/"
] | I have a problem. I need to list only 2 roles: customer and shop\_manager. 1. How can i do that with this script?
```
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
``` | No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now. |
250,521 | <p>I have an issue reaching my Wordpress login page. <a href="http://www.everydaytherapy.ie/wp-admin" rel="nofollow noreferrer">http://www.everydaytherapy.ie/wp-admin</a>
I am redirected and a drop down menu appears to login in. But not the proper Wordpress login screen (check the URL yourself). I still tried to login but my details didn't work for it. It would just reset. I have tried deleting the .htaccess file, adding the URL's to the config.php file and anything else I could find online. I went into phpMyadmin and the tables seem correct. I deactivated all my plugin's and even my theme and still the same issue.
Any help would be greatly appreciated!</p>
| [
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-... | 2016/12/28 | [
"https://wordpress.stackexchange.com/questions/250521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100619/"
] | I have an issue reaching my Wordpress login page. <http://www.everydaytherapy.ie/wp-admin>
I am redirected and a drop down menu appears to login in. But not the proper Wordpress login screen (check the URL yourself). I still tried to login but my details didn't work for it. It would just reset. I have tried deleting the .htaccess file, adding the URL's to the config.php file and anything else I could find online. I went into phpMyadmin and the tables seem correct. I deactivated all my plugin's and even my theme and still the same issue.
Any help would be greatly appreciated! | No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now. |
250,529 | <p>I've finally figured out how the post loop works (very new to coding), and I'm trying to figure out the best way to add a class to individual posts I'm displaying (title, author, etc when I add all of them) in the following code:</p>
<pre><code> $args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo $recent["the_post_thumbnail"];
echo '<ul><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </ul> ';?>
<ul><?php echo $recent["post_excerpt"];?></ul>
<?php
}
wp_reset_query();
?>
<?php
</code></pre>
| [
{
"answer_id": 250534,
"author": "jetyet47",
"author_id": 91783,
"author_profile": "https://wordpress.stackexchange.com/users/91783",
"pm_score": 2,
"selected": false,
"text": "<p>Not totally clear what you're asking, but post_class is probably your best bet.</p>\n\n<pre><code><?php p... | 2016/12/28 | [
"https://wordpress.stackexchange.com/questions/250529",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] | I've finally figured out how the post loop works (very new to coding), and I'm trying to figure out the best way to add a class to individual posts I'm displaying (title, author, etc when I add all of them) in the following code:
```
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo $recent["the_post_thumbnail"];
echo '<ul><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </ul> ';?>
<ul><?php echo $recent["post_excerpt"];?></ul>
<?php
}
wp_reset_query();
?>
<?php
``` | Not totally clear what you're asking, but post\_class is probably your best bet.
```
<?php post_class(); ?>
```
More info: <https://codex.wordpress.org/Function_Reference/post_class> |