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
|
---|---|---|---|---|---|---|
202,121 |
<p>I need to import catalog data from external server.
The data is arranged in categories and then items.</p>
<p>the API requires the following calls:
1. Get categories
2. Get category items
3. get item data</p>
<p>this task works once a day by using a cron job.
the catalog contains about 5000 items.</p>
<p>items import is encapsulated into 3 files:
1. get cats - gets all categories
2. get category items - gets all the items, creates each item (cpt) and than calls 3
3. get item info - updates the item data (custom fields)</p>
<p>no matter what I do, I'm getting at some point error 504 Gateway Time-out.</p>
<p>How can I bypass that ?</p>
<p>script 1:</p>
<pre><code> <?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(600);
$processed_cats = array();
$processed_items = array();
$cats = get_terms( 'svod_cat', array('hide_empty' => false));
foreach ($cats as $cat) {
if (get_field('disabled', 'svod_cat_'.$cat->term_id))
continue;
$cat_id = get_field('cat_id', 'svod_cat_'.$cat->term_id);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://example.com/import_cat.php?cat_id='.$cat->term_id);
curl_exec ($curl);
curl_close ($curl);
echo $res."<br/>";
}
svod_update_disabled_items($processed_items);
?>
</code></pre>
<p>script 2:</p>
<pre><code> <?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(3600);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$wp_cat = $_GET['cat_id'];
function svod_get_items_list($cat) {
$url = 'http://clientserver.com/getmyitems.php?cat=$cat';
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$items_json = curl_exec ($curl);
curl_close ($curl);
$items = json_decode($items_json);
return $items->results;
}
function svod_get_items($svod_cat, $wp_cat) {
global $processed_items;
$new = 0;
$update = 0;
$items = svod_get_items_list($svod_cat);
echo "Got items list with ".count($items)." items<br/>";
flush();
foreach ($items as $item) {
if (($my_item = get_page_by_title( $item->VodTitle, OBJECT, 'svod_item')) == NULL) {
$id = svod_create_new_item($item, $wp_cat);
$new++;
} else {
$id= svod_update_item($my_item, $item, $wp_cat);
$update++;
}
$url = "http://example.com/import_item.php?item_id=$id";
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec ($curl);
curl_close ($curl);
$processed_items[] = $id;
echo $item->vodId . " ".$res."<br/>";
flush();
}
echo "Done import; created $new, updated $update<br/>";
flush();
}
function svod_create_new_item($item, $wp_cat) {
$my_post = array(
'post_title' => $item->VodTitle,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'svod_item'
);
$pid = wp_insert_post($my_post);
if (!is_wp_error($pid)) {
wp_set_post_terms( $pid, array($wp_cat), 'svod_cat', true);
update_field('field_55ec1ed404c0e', $item->VodId, $pid);
}
return $pid;
}
function svod_update_item($my_item, $item, $wp_cat) {
wp_set_post_terms( $my_item->ID, array($wp_cat), 'svod_cat', true);
update_field('field_55ec1ed404c0e', $item->VodId, $pid);
return $my_item->ID;
}
$processed_items = array();
echo "Importing category ".$wp_cat.'<br/>';
$cat_id = get_field('cat_id', 'svod_cat_'.$wp_cat);
svod_get_items($cat_id, $wp_cat);
?>
</code></pre>
<p>script 3:</p>
<pre><code> <?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(60);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function svod_get_item_info($vodid) {
$url = 'https://clientserver.com/get_info.php?id='.$id;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$item_json = curl_exec ($curl);
curl_close ($curl);
$item = json_decode($item_json);
return $item;
}
function svod_update_item($pid, $info) {
$my_post = array(
'ID' => $pid,
'post_content' => $info->VodDesc,
);
// Update the post into the database
wp_update_post( $my_post );
update_field('field_55ec08a2bc9bf', $info->VodReleaseYear, $pid );
update_field('field_55ec08a9bc9c0', $info->VodRating, $pid);
update_field('field_55ec08c4bc9c1', $info->VodRunTime, $pid);
update_field('field_55ec091bbc9c2', $info->VodPosterUrl, $pid);
update_field('field_55ec15f4bc9c3', ($info->VodHD == 'true'), $pid);
}
$wp_vod_id = $_GET['item_id'];
$vod_id = get_field('vod_id', $wp_vod_id);
$info = svod_get_item_info($vod_id);
svod_update_item($wp_vod_id, $info);
echo "<br/>Item updated !";
?>
</code></pre>
|
[
{
"answer_id": 202123,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p><code>set_time_limit(0)</code> will disable the time limit check and should solve the problem if that is the actual issue. You can also try and sent multiple requests at the same time with curl which should make things faster.</p>\n"
},
{
"answer_id": 202147,
"author": "Dips Kakadiya",
"author_id": 57167,
"author_profile": "https://wordpress.stackexchange.com/users/57167",
"pm_score": 1,
"selected": false,
"text": "<p>For avoid timeout best option is wp-cli.\nWp-cli is wordpress command line interface. you can export/import data using wp-cli.</p>\n"
},
{
"answer_id": 202149,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 1,
"selected": false,
"text": "<p>I would <strong>split those operations into several actions</strong>. If it's impossible to finish it in one run, there won't be any better solution. The main thing is if the error is caused by client server timeout (unable to download all data in time), or your server timeout (unable to process all data in time). Another uknown thing is what operation is the most time consuming. Script 3?</p>\n\n<p>I would create some <strong>custom DB tables</strong>. Then run cronjob to download all categories and save them to one table, then another cronjob to download items list. And then cronjob, that takes every 5 minutes for example 10 items from list, and download its \"item info\"... until every item has its info. In that moment you have all \"source\" data from client server.</p>\n\n<p>After this, you can run another operation <strong>to process saved data</strong> and import them to your WP (probably not all in bulk, but again splitted into more runs). Processed items will be removed from table, and when it's empty, import is DONE. If some run fails/timeouts, items will stay in DB table, and waits until another run. Nothing will be lost.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/395/"
] |
I need to import catalog data from external server.
The data is arranged in categories and then items.
the API requires the following calls:
1. Get categories
2. Get category items
3. get item data
this task works once a day by using a cron job.
the catalog contains about 5000 items.
items import is encapsulated into 3 files:
1. get cats - gets all categories
2. get category items - gets all the items, creates each item (cpt) and than calls 3
3. get item info - updates the item data (custom fields)
no matter what I do, I'm getting at some point error 504 Gateway Time-out.
How can I bypass that ?
script 1:
```
<?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(600);
$processed_cats = array();
$processed_items = array();
$cats = get_terms( 'svod_cat', array('hide_empty' => false));
foreach ($cats as $cat) {
if (get_field('disabled', 'svod_cat_'.$cat->term_id))
continue;
$cat_id = get_field('cat_id', 'svod_cat_'.$cat->term_id);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://example.com/import_cat.php?cat_id='.$cat->term_id);
curl_exec ($curl);
curl_close ($curl);
echo $res."<br/>";
}
svod_update_disabled_items($processed_items);
?>
```
script 2:
```
<?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(3600);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$wp_cat = $_GET['cat_id'];
function svod_get_items_list($cat) {
$url = 'http://clientserver.com/getmyitems.php?cat=$cat';
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$items_json = curl_exec ($curl);
curl_close ($curl);
$items = json_decode($items_json);
return $items->results;
}
function svod_get_items($svod_cat, $wp_cat) {
global $processed_items;
$new = 0;
$update = 0;
$items = svod_get_items_list($svod_cat);
echo "Got items list with ".count($items)." items<br/>";
flush();
foreach ($items as $item) {
if (($my_item = get_page_by_title( $item->VodTitle, OBJECT, 'svod_item')) == NULL) {
$id = svod_create_new_item($item, $wp_cat);
$new++;
} else {
$id= svod_update_item($my_item, $item, $wp_cat);
$update++;
}
$url = "http://example.com/import_item.php?item_id=$id";
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec ($curl);
curl_close ($curl);
$processed_items[] = $id;
echo $item->vodId . " ".$res."<br/>";
flush();
}
echo "Done import; created $new, updated $update<br/>";
flush();
}
function svod_create_new_item($item, $wp_cat) {
$my_post = array(
'post_title' => $item->VodTitle,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'svod_item'
);
$pid = wp_insert_post($my_post);
if (!is_wp_error($pid)) {
wp_set_post_terms( $pid, array($wp_cat), 'svod_cat', true);
update_field('field_55ec1ed404c0e', $item->VodId, $pid);
}
return $pid;
}
function svod_update_item($my_item, $item, $wp_cat) {
wp_set_post_terms( $my_item->ID, array($wp_cat), 'svod_cat', true);
update_field('field_55ec1ed404c0e', $item->VodId, $pid);
return $my_item->ID;
}
$processed_items = array();
echo "Importing category ".$wp_cat.'<br/>';
$cat_id = get_field('cat_id', 'svod_cat_'.$wp_cat);
svod_get_items($cat_id, $wp_cat);
?>
```
script 3:
```
<?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
set_time_limit(60);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function svod_get_item_info($vodid) {
$url = 'https://clientserver.com/get_info.php?id='.$id;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$item_json = curl_exec ($curl);
curl_close ($curl);
$item = json_decode($item_json);
return $item;
}
function svod_update_item($pid, $info) {
$my_post = array(
'ID' => $pid,
'post_content' => $info->VodDesc,
);
// Update the post into the database
wp_update_post( $my_post );
update_field('field_55ec08a2bc9bf', $info->VodReleaseYear, $pid );
update_field('field_55ec08a9bc9c0', $info->VodRating, $pid);
update_field('field_55ec08c4bc9c1', $info->VodRunTime, $pid);
update_field('field_55ec091bbc9c2', $info->VodPosterUrl, $pid);
update_field('field_55ec15f4bc9c3', ($info->VodHD == 'true'), $pid);
}
$wp_vod_id = $_GET['item_id'];
$vod_id = get_field('vod_id', $wp_vod_id);
$info = svod_get_item_info($vod_id);
svod_update_item($wp_vod_id, $info);
echo "<br/>Item updated !";
?>
```
|
For avoid timeout best option is wp-cli.
Wp-cli is wordpress command line interface. you can export/import data using wp-cli.
|
202,124 |
<p>I have a bash script that installs and activates a theme like this: </p>
<p>wp theme install <a href="https://bitbucket.org/organization/theme/get/master.zip" rel="nofollow">https://bitbucket.org/organization/theme/get/master.zip</a> --activate</p>
<p>The problem is that it only works with public repositories, rather than private ones. If I make the repository private I get this error: </p>
<pre><code>Unpacking the package...
Warning: The package could not be installed. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature
</code></pre>
<p>Is there a way I can install private repositories that I have ssh keys and passwords for?</p>
|
[
{
"answer_id": 202130,
"author": "chap",
"author_id": 48204,
"author_profile": "https://wordpress.stackexchange.com/users/48204",
"pm_score": 3,
"selected": true,
"text": "<p>I actually figured out a way to do this. First you use wget like this: </p>\n\n<pre><code>wget --user username --ask-password -O path/to/output.zip https://bitbucket.org/path/to/file.zip\n</code></pre>\n\n<p>the -O flag specifies output and output.zip is where you want it to download to.</p>\n\n<p>Then you can run:</p>\n\n<pre><code>wp theme install path/to/output.zip --activate\n</code></pre>\n\n<p>Happy days</p>\n"
},
{
"answer_id": 210562,
"author": "JJ Rohrer",
"author_id": 8972,
"author_profile": "https://wordpress.stackexchange.com/users/8972",
"pm_score": 1,
"selected": false,
"text": "<p>I like to run my grab from a php script. I happen to do git clone instead of wget, but the same principals will still apply. Try something like this:</p>\n\n<pre><code>git clone \"https://bitBucketUsername:[email protected]/organization/theme/get/master.git\"\n</code></pre>\n\n<p>In practice, you'll need to escape your username and password, like so.</p>\n\n<pre><code>$bitBucketUsername = \"[email protected]\";\n$bitBucketPassword = 'ILikeTurtles';\n$bitBucketCredentials = urlencode($bitBucketUsername).':'.urlencode($bitBucketPassword).'@';\n$cmd = \"git clone \\\"https://{$bitBucketCredentials}bitbucket.org/organization/theme/get/master.git\\\"\";\n\nexec($cmd, $output, $return);\nif ($return != 0) {\n if (is_array($output)) {\n $output = var_export($output, true);\n }\n print \"Yikes, got ($return). output: $output\";\n} else {\n // seems to have worked\n // maybe activate the plugin?\n}\n</code></pre>\n\n<p>For a more secure solution when using git, search on 'helper credentials'</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202124",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48204/"
] |
I have a bash script that installs and activates a theme like this:
wp theme install <https://bitbucket.org/organization/theme/get/master.zip> --activate
The problem is that it only works with public repositories, rather than private ones. If I make the repository private I get this error:
```
Unpacking the package...
Warning: The package could not be installed. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature
```
Is there a way I can install private repositories that I have ssh keys and passwords for?
|
I actually figured out a way to do this. First you use wget like this:
```
wget --user username --ask-password -O path/to/output.zip https://bitbucket.org/path/to/file.zip
```
the -O flag specifies output and output.zip is where you want it to download to.
Then you can run:
```
wp theme install path/to/output.zip --activate
```
Happy days
|
202,127 |
<pre><code><?php
/**
* The template for displaying comments.
*
* The area of the page that contains both current comments
* and the comment form.
*
* @package Tesseract
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( '1 Comment on &ldquo;%2$s&rdquo;', '%1$s Comments on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'tesseract' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
'avatar_size' => 80
) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'tesseract' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
</code></pre>
|
[
{
"answer_id": 202128,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": false,
"text": "<p>You needed to move <code><?php comment_form(); ?></code> at the top, just above comment header title.</p>\n\n<p>Here is the modified code.</p>\n\n<pre><code><?php\n/**\n * The template for displaying comments.\n *\n * The area of the page that contains both current comments\n * and the comment form.\n *\n * @package Tesseract\n */\n\n/*\n * If the current post is protected by a password and\n * the visitor has not yet entered the password we will\n * return early without loading the comments.\n */\nif ( post_password_required() ) {\n return;\n}\n?>\n\n<div id=\"comments\" class=\"comments-area\">\n\n <?php // You can start editing here -- including this comment! ?>\n\n <?php comment_form(); ?>\n\n <?php if ( have_comments() ) : ?>\n <h2 class=\"comments-title\">\n <?php\n printf( _nx( '1 Comment on &ldquo;%2$s&rdquo;', '%1$s Comments on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'tesseract' ),\n number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );\n ?>\n </h2>\n\n <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>\n <nav id=\"comment-nav-above\" class=\"comment-navigation\" role=\"navigation\">\n <h1 class=\"screen-reader-text\"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>\n <div class=\"nav-previous\"><?php previous_comments_link( __( '&larr; Older Comments', 'tesseract' ) ); ?></div>\n <div class=\"nav-next\"><?php next_comments_link( __( 'Newer Comments &rarr;', 'tesseract' ) ); ?></div>\n </nav><!-- #comment-nav-above -->\n <?php endif; // check for comment navigation ?>\n\n <ol class=\"comment-list\">\n <?php\n wp_list_comments( array(\n 'style' => 'ol',\n 'short_ping' => true,\n 'avatar_size' => 80\n ) );\n ?>\n </ol><!-- .comment-list -->\n\n <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>\n <nav id=\"comment-nav-below\" class=\"comment-navigation\" role=\"navigation\">\n <h1 class=\"screen-reader-text\"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>\n <div class=\"nav-previous\"><?php previous_comments_link( __( '&larr; Older Comments', 'tesseract' ) ); ?></div>\n <div class=\"nav-next\"><?php next_comments_link( __( 'Newer Comments &rarr;', 'tesseract' ) ); ?></div>\n </nav><!-- #comment-nav-below -->\n <?php endif; // check for comment navigation ?>\n\n <?php endif; // have_comments() ?>\n\n <?php\n // If comments are closed and there are comments, let's leave a little note, shall we?\n if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :\n ?>\n <p class=\"no-comments\"><?php _e( 'Comments are closed.', 'tesseract' ); ?></p>\n <?php endif; ?>\n\n</div><!-- #comments -->\n</code></pre>\n"
},
{
"answer_id": 202138,
"author": "Ahir Hemant",
"author_id": 80066,
"author_profile": "https://wordpress.stackexchange.com/users/80066",
"pm_score": -1,
"selected": false,
"text": "<p>Paste this code where you need to display: </p>\n\n<pre><code>comment_form();\n</code></pre>\n"
},
{
"answer_id": 272888,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>comments box above comments for change in <strong>comment.php</strong> file in your <strong>current active theme</strong>. if you <strong>use child theme then put this file in child</strong> after then change it.</p>\n\n<p>In comment.php file find <code>comment_form();</code> after then cut this line and past after this line <code><div id=\"comments\" class=\"comments-area\"></code></p>\n\n<p>like that : </p>\n\n<pre><code><div id=\"comments\" class=\"comments-area\">\n\n <?php\n comment_form();\n // You can start editing here -- including this comment!\n if ( have_comments() ) : ?>\n <h2 class=\"comments-title\">\n</code></pre>\n"
},
{
"answer_id": 411262,
"author": "Shadmehri Iman",
"author_id": 227472,
"author_profile": "https://wordpress.stackexchange.com/users/227472",
"pm_score": 0,
"selected": false,
"text": "<p>Place <code><?php comment_form(); ?></code> above <code><ol class="comment-list"></code>.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80103/"
] |
```
<?php
/**
* The template for displaying comments.
*
* The area of the page that contains both current comments
* and the comment form.
*
* @package Tesseract
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( '1 Comment on “%2$s”', '%1$s Comments on “%2$s”', get_comments_number(), 'comments title', 'tesseract' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
'avatar_size' => 80
) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'tesseract' ); ?></p>
<?php endif; ?>
<?php comment_form(); ?>
</div><!-- #comments -->
```
|
You needed to move `<?php comment_form(); ?>` at the top, just above comment header title.
Here is the modified code.
```
<?php
/**
* The template for displaying comments.
*
* The area of the page that contains both current comments
* and the comment form.
*
* @package Tesseract
*/
/*
* If the current post is protected by a password and
* the visitor has not yet entered the password we will
* return early without loading the comments.
*/
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="comments-area">
<?php // You can start editing here -- including this comment! ?>
<?php comment_form(); ?>
<?php if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( _nx( '1 Comment on “%2$s”', '%1$s Comments on “%2$s”', get_comments_number(), 'comments title', 'tesseract' ),
number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
?>
</h2>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-above" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-above -->
<?php endif; // check for comment navigation ?>
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
'avatar_size' => 80
) );
?>
</ol><!-- .comment-list -->
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
<nav id="comment-nav-below" class="comment-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Comment navigation', 'tesseract' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', 'tesseract' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', 'tesseract' ) ); ?></div>
</nav><!-- #comment-nav-below -->
<?php endif; // check for comment navigation ?>
<?php endif; // have_comments() ?>
<?php
// If comments are closed and there are comments, let's leave a little note, shall we?
if ( ! comments_open() && '0' != get_comments_number() && post_type_supports( get_post_type(), 'comments' ) ) :
?>
<p class="no-comments"><?php _e( 'Comments are closed.', 'tesseract' ); ?></p>
<?php endif; ?>
</div><!-- #comments -->
```
|
202,134 |
<p>I have a custom post type called <code>dramas</code></p>
<pre><code>/******* DRAMAS BEGIN *****************************************/
register_post_type('dramas', array(
'label' => 'Dramas',
'show_ui' => true,
'supports' => array('title', 'thumbnail', 'description'),
'labels' => array (
'name' => 'Dramas',
'singular_name' => 'Drama',
'menu_name' => 'Dramas'
),
'rewrite' => array( 'slug' => 'drama' ),
) );
</code></pre>
<p>I have set up a custom <code>taxonomy</code> for the post</p>
<pre><code>/* register taxonomy only for DRAMAS*/
register_taxonomy(
'drama_taxonomy',
'dramas',
array(
'hierarchical' => true,
'label' => 'Category',
'query_var' => true,
'rewrite' => true
)
);
</code></pre>
<p>I am able to get these post anywhere using following code</p>
<pre><code><?php
$args = array( 'post_type' => 'dramas', 'posts_per_page' => 4 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'drama_realityshow_home_page_thumb', true);
$terms = get_the_terms( $post->ID, 'drama_taxonomy' );
?>
<div class="prime-item">
<a href="<?php the_permalink(); ?>" target="_blank" class="standard-height">
<img src="<?php echo $image_url[0]; ?>" width="300" height="168" class="hoverZoomLink">
</a>
<div class="new-cat"><?php
foreach($terms as $term) {
echo $term->name;
} ?>
</div>
</div>
<?php endwhile; ?>
</code></pre>
<p>By using the above code I am getting <code>dramas</code> custom post type's </p>
<ol>
<li>Thumbnail source</li>
<li>Taxonomy term</li>
<li>Permalink</li>
</ol>
<p>When I hover over the <strong></strong> I see the permalink / url <code>www.mysite.com/drama/post-name</code> at the browser bottom as I expected.
But when I click on the link [ 'a' tag in the <code><div class="prime-item"></code>] I am getting 404 page.</p>
<p>I have <code>single-dramas.php</code> in the theme folder. Even if I don not have that it should fall to <code>single.php</code> but it's not.</p>
<p>The browser address bar shows <code>www.mysite.com/drama/post-name</code> but displaying 404.</p>
<p>Also permalink edit option is NOT found at the right bottom of the editor title as always it's appeared.</p>
<p><a href="https://i.stack.imgur.com/IWdX0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IWdX0.png" alt="PERMALINK EDITOR"></a></p>
<p>why is this?
How can I get to single page / the permalink works for the post type <code>dramas</code>? NOT to go to 404.</p>
|
[
{
"answer_id": 202142,
"author": "Riffaz Starr",
"author_id": 43764,
"author_profile": "https://wordpress.stackexchange.com/users/43764",
"pm_score": 3,
"selected": true,
"text": "<p>You custom post type is <strong>NO</strong>T public.</p>\n\n<p>Add following lines to your <strong>register_post_type</strong> <code>array</code></p>\n\n<pre><code>'public' => true,\n'publicly_queryable' => true, \n</code></pre>\n"
},
{
"answer_id": 202144,
"author": "Dips Kakadiya",
"author_id": 57167,
"author_profile": "https://wordpress.stackexchange.com/users/57167",
"pm_score": 1,
"selected": false,
"text": "<p>Your custom post type is not publicly visible so you need to update your argument</p>\n\n<p>You can refer given link for that <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>And if your custom post type publicly visible and still problem exist please Flush your permalink and try it.\nIt will solve your problem.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69828/"
] |
I have a custom post type called `dramas`
```
/******* DRAMAS BEGIN *****************************************/
register_post_type('dramas', array(
'label' => 'Dramas',
'show_ui' => true,
'supports' => array('title', 'thumbnail', 'description'),
'labels' => array (
'name' => 'Dramas',
'singular_name' => 'Drama',
'menu_name' => 'Dramas'
),
'rewrite' => array( 'slug' => 'drama' ),
) );
```
I have set up a custom `taxonomy` for the post
```
/* register taxonomy only for DRAMAS*/
register_taxonomy(
'drama_taxonomy',
'dramas',
array(
'hierarchical' => true,
'label' => 'Category',
'query_var' => true,
'rewrite' => true
)
);
```
I am able to get these post anywhere using following code
```
<?php
$args = array( 'post_type' => 'dramas', 'posts_per_page' => 4 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'drama_realityshow_home_page_thumb', true);
$terms = get_the_terms( $post->ID, 'drama_taxonomy' );
?>
<div class="prime-item">
<a href="<?php the_permalink(); ?>" target="_blank" class="standard-height">
<img src="<?php echo $image_url[0]; ?>" width="300" height="168" class="hoverZoomLink">
</a>
<div class="new-cat"><?php
foreach($terms as $term) {
echo $term->name;
} ?>
</div>
</div>
<?php endwhile; ?>
```
By using the above code I am getting `dramas` custom post type's
1. Thumbnail source
2. Taxonomy term
3. Permalink
When I hover over the I see the permalink / url `www.mysite.com/drama/post-name` at the browser bottom as I expected.
But when I click on the link [ 'a' tag in the `<div class="prime-item">`] I am getting 404 page.
I have `single-dramas.php` in the theme folder. Even if I don not have that it should fall to `single.php` but it's not.
The browser address bar shows `www.mysite.com/drama/post-name` but displaying 404.
Also permalink edit option is NOT found at the right bottom of the editor title as always it's appeared.
[](https://i.stack.imgur.com/IWdX0.png)
why is this?
How can I get to single page / the permalink works for the post type `dramas`? NOT to go to 404.
|
You custom post type is **NO**T public.
Add following lines to your **register\_post\_type** `array`
```
'public' => true,
'publicly_queryable' => true,
```
|
202,143 |
<p>I have to do something but I just can't come up with a way to do it.<br><br>
On one hand I have created pages who are companies. So every page is a company-page.<br>
On the other hand I have created users who have a custom field added to their profile that holds the name of the company they work at.</p>
<p>No this is merely a connection between those two. So I came to the conclusion that if a company is deleted the users should be to, or at least a message should appear that the company can't be deleted because there are still users that are connected to the company.</p>
<p>I think I should hook in some sort of function to add an action to the page-delete button.</p>
<p>It's almost like if you delete a user and WP asks you if the posts the user has made are assigned to another user.</p>
<p>Can anybody tell me more about this or share some thoughts/ideas?</p>
<p>===================================<br>
UPDATE<br>
So I created the following for a custom_function to hook in the <code>before_delete_post</code><br>
NOTE: this is tested on a company page for output purposes. I use a <code>$_GET["company"]</code> request because the name is passed on in the URL. </p>
<pre><code>global $post;
$company = $_GET['company'];
$employees = $wpdb->get_results("
SELECT meta_value
FROM $wpdb->usermeta
WHERE meta_key = 'company'
AND meta_value='$company'"
);
/*
output $employees:
[0] => stdClass Object
(
[meta_value] => company_name
)
*/
if(in_array($company, $employees)){
echo 'Yes';
}else{
echo 'No';
}
</code></pre>
<p>Let's say I want to delete the page <code>company_name</code>. What I do is see if this name is in the <code>usermeta</code> table. If this is true the delete function should not be executed. If not the page can be deleted.</p>
<p>But this just keeps echo-ing <code>No</code> while it should echo <code>Yes</code> because I know the pagename is <code>company_name</code> and it is in the employee list. So I should have a match.</p>
|
[
{
"answer_id": 202152,
"author": "Arjan Kuiken",
"author_id": 76871,
"author_profile": "https://wordpress.stackexchange.com/users/76871",
"pm_score": 0,
"selected": false,
"text": "<p>this can be best solved by adding constraints in your database schemes. The best way to achieve this is by adding a foreign key constraint which reacts on the \"DELETE\" action. \nFor more info about the foreign key read: <a href=\"http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html</a></p>\n\n<p>You could also do a SELECT before calling the DELETE action and if it returns users exit the function with a error of some kind.</p>\n"
},
{
"answer_id": 202247,
"author": "Iamzozo",
"author_id": 20122,
"author_profile": "https://wordpress.stackexchange.com/users/20122",
"pm_score": 2,
"selected": true,
"text": "<p>It gives an array with objects. So <code>in_array()</code> won't find anything, you have to convert it before. After you get the results from wbdb:</p>\n\n<pre><code>$employees_array = array();\nforeach($employees as $employee) {\n $employees_array[] = $employee->meta_value;\n}\n\nif(in_array($company, $employees_array)) {\n ...\n}\n</code></pre>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52240/"
] |
I have to do something but I just can't come up with a way to do it.
On one hand I have created pages who are companies. So every page is a company-page.
On the other hand I have created users who have a custom field added to their profile that holds the name of the company they work at.
No this is merely a connection between those two. So I came to the conclusion that if a company is deleted the users should be to, or at least a message should appear that the company can't be deleted because there are still users that are connected to the company.
I think I should hook in some sort of function to add an action to the page-delete button.
It's almost like if you delete a user and WP asks you if the posts the user has made are assigned to another user.
Can anybody tell me more about this or share some thoughts/ideas?
===================================
UPDATE
So I created the following for a custom\_function to hook in the `before_delete_post`
NOTE: this is tested on a company page for output purposes. I use a `$_GET["company"]` request because the name is passed on in the URL.
```
global $post;
$company = $_GET['company'];
$employees = $wpdb->get_results("
SELECT meta_value
FROM $wpdb->usermeta
WHERE meta_key = 'company'
AND meta_value='$company'"
);
/*
output $employees:
[0] => stdClass Object
(
[meta_value] => company_name
)
*/
if(in_array($company, $employees)){
echo 'Yes';
}else{
echo 'No';
}
```
Let's say I want to delete the page `company_name`. What I do is see if this name is in the `usermeta` table. If this is true the delete function should not be executed. If not the page can be deleted.
But this just keeps echo-ing `No` while it should echo `Yes` because I know the pagename is `company_name` and it is in the employee list. So I should have a match.
|
It gives an array with objects. So `in_array()` won't find anything, you have to convert it before. After you get the results from wbdb:
```
$employees_array = array();
foreach($employees as $employee) {
$employees_array[] = $employee->meta_value;
}
if(in_array($company, $employees_array)) {
...
}
```
|
202,159 |
<p>I created a custom taxonomy using following code.</p>
<pre><code>add_action( 'init', 'schedule_day_tax_func' );
function schedule_day_tax_func() {
register_taxonomy(
'schedule_day_taxonomy',
'schedule',
array(
'hierarchical' => true,
'label' => 'Day',
'query_var' => true,
'orderby' => 'ID',
)
);
}
</code></pre>
<p>after I added some terms from the admin panel, the TERMS displayed in <code>alphabetica</code>l order in admin panel. </p>
<p><a href="https://i.stack.imgur.com/vbbZN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vbbZN.jpg" alt="img"></a></p>
<p>I want those in orderby <code>ID</code> or by the <code>entered</code> order.
How can I do that?</p>
|
[
{
"answer_id": 202189,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>Method #1 - Modifying the query arguments</h2>\n\n<p>If we want to modify the <em>term order</em> for the <code>schedule_day_taxonomy</code> term checklist, on the single <code>schedule</code> cpt edit screen, then we can use the following setup:</p>\n\n<pre><code>add_action( 'load-post.php', function()\n{\n add_filter( 'wp_terms_checklist_args', 'wpse_terms_checklist_args' );\n} );\n\nfunction wpse_terms_checklist_args( $args )\n{ \n // Target the 'schedule' custom post type edit screen\n if( 'schedule' === get_current_screen()->id )\n add_filter( 'get_terms_args', 'wpse_terms_args', 10, 2 );\n return $args;\n}\n\nfunction wpse_terms_args( $args, $taxonomies )\n{\n // Target the 'all' tab in the 'schedule_day_taxonomy' terms check list \n if(\n isset( $args['get'] )\n && 'all' === $args['get']\n && isset( $taxonomies[0] )\n && 'schedule_day_taxonomy' === $taxonomies[0]\n ) {\n // Modify the term order\n $args['orderby'] = 'ID'; // <-- Adjust this to your needs!\n $args['order'] = 'ASC'; // <-- Adjust this to your needs!\n\n // House cleaning - Remove the filter callbacks\n remove_filter( current_filter(), __FUNCTION__ ); \n remove_filter( 'wp_terms_checklist_args', 'wpse_terms_checklist_args' );\n }\n return $args;\n}\n</code></pre>\n\n<p>Another possibility would be to combine this into a single <code>get_terms_args</code> filter callback.</p>\n\n<p>To get the following day order:</p>\n\n<pre><code>Sun, Mon, Tue, Wed, Thu, Fri, Sat\n</code></pre>\n\n<p>we could modify the corresponding term slugs and use:</p>\n\n<pre><code>// Modify the term order\n$args['orderby'] = 'slug'; \n$args['order'] = 'ASC'; \n</code></pre>\n\n<h2>Method #2 - Re-ordering the query results</h2>\n\n<p>If we don't want to modify the slug, then here's another approach.</p>\n\n<p>We can re-order the resulting terms array, in the same order as the localized weekdays.</p>\n\n<pre><code>add_filter( 'wp_terms_checklist_args', function( $args )\n{ \n add_filter( 'get_terms', 'wpse_get_terms', 10, 3 );\n return $args;\n} );\n\nfunction wpse_get_terms( $terms, $taxonomies, $args )\n{\n if( isset( $taxonomies[0] )\n && 'schedule_day_taxonomy' === $taxonomies[0]\n && 'schedule' === get_current_screen()->id\n ) {\n $newterms = [];\n foreach( (array) $GLOBALS['wp_locale']->weekday as $day )\n {\n foreach( (array) $terms as $term )\n {\n if( $term->name === $day )\n $newterms[] = $term;\n }\n }\n remove_filter( current_filter(), __FUNCTION__ );\n if( 7 === count( $newterms ) )\n $terms = $newterms;\n }\n return $terms;\n}\n</code></pre>\n\n<p>We could also replace</p>\n\n<pre><code>$GLOBALS['wp_locale']->weekday\n</code></pre>\n\n<p>with a custom weekdays array, ordered in a custom way.</p>\n\n<p>Here's the <em>English</em> version:</p>\n\n<p><a href=\"https://i.stack.imgur.com/S1YYp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S1YYp.jpg\" alt=\"English\"></a></p>\n\n<p>and here's the <em>Icelandic</em> version:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BYtjD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BYtjD.jpg\" alt=\"Icelandic\"></a></p>\n\n<h2>Method #3 - Custom SQL ordering</h2>\n\n<p>We could modify the SQL ordering with the <code>get_terms_orderby</code> filter, with a <code>CASE/WHEN/THEN</code> setup.</p>\n\n<p>Hopefully you can adjust this to your needs.</p>\n"
},
{
"answer_id": 285536,
"author": "Lucas Gabriel",
"author_id": 27812,
"author_profile": "https://wordpress.stackexchange.com/users/27812",
"pm_score": 0,
"selected": false,
"text": "<p>I found the solution at this link: <a href=\"https://core.trac.wordpress.org/ticket/34996\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/34996</a></p>\n\n<pre><code>public function pre_get_terms( $query ) {\n $meta_query_args = array(\n 'relation' => 'AND', // Optional, defaults to \"AND\"\n array(\n 'key' => 'order_index',\n 'value' => 0,\n 'compare' => '>='\n )\n );\n $meta_query = new WP_Meta_Query( $meta_query_args );\n $query->meta_query = $meta_query;\n $query->orderby = 'position_clause';\n}\n</code></pre>\n\n<p>The answer was in the comment of @eherman24. all you need to adapt is adding an action <code>pre_get_terms</code> and then use the above function.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202159",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69828/"
] |
I created a custom taxonomy using following code.
```
add_action( 'init', 'schedule_day_tax_func' );
function schedule_day_tax_func() {
register_taxonomy(
'schedule_day_taxonomy',
'schedule',
array(
'hierarchical' => true,
'label' => 'Day',
'query_var' => true,
'orderby' => 'ID',
)
);
}
```
after I added some terms from the admin panel, the TERMS displayed in `alphabetica`l order in admin panel.
[](https://i.stack.imgur.com/vbbZN.jpg)
I want those in orderby `ID` or by the `entered` order.
How can I do that?
|
Method #1 - Modifying the query arguments
-----------------------------------------
If we want to modify the *term order* for the `schedule_day_taxonomy` term checklist, on the single `schedule` cpt edit screen, then we can use the following setup:
```
add_action( 'load-post.php', function()
{
add_filter( 'wp_terms_checklist_args', 'wpse_terms_checklist_args' );
} );
function wpse_terms_checklist_args( $args )
{
// Target the 'schedule' custom post type edit screen
if( 'schedule' === get_current_screen()->id )
add_filter( 'get_terms_args', 'wpse_terms_args', 10, 2 );
return $args;
}
function wpse_terms_args( $args, $taxonomies )
{
// Target the 'all' tab in the 'schedule_day_taxonomy' terms check list
if(
isset( $args['get'] )
&& 'all' === $args['get']
&& isset( $taxonomies[0] )
&& 'schedule_day_taxonomy' === $taxonomies[0]
) {
// Modify the term order
$args['orderby'] = 'ID'; // <-- Adjust this to your needs!
$args['order'] = 'ASC'; // <-- Adjust this to your needs!
// House cleaning - Remove the filter callbacks
remove_filter( current_filter(), __FUNCTION__ );
remove_filter( 'wp_terms_checklist_args', 'wpse_terms_checklist_args' );
}
return $args;
}
```
Another possibility would be to combine this into a single `get_terms_args` filter callback.
To get the following day order:
```
Sun, Mon, Tue, Wed, Thu, Fri, Sat
```
we could modify the corresponding term slugs and use:
```
// Modify the term order
$args['orderby'] = 'slug';
$args['order'] = 'ASC';
```
Method #2 - Re-ordering the query results
-----------------------------------------
If we don't want to modify the slug, then here's another approach.
We can re-order the resulting terms array, in the same order as the localized weekdays.
```
add_filter( 'wp_terms_checklist_args', function( $args )
{
add_filter( 'get_terms', 'wpse_get_terms', 10, 3 );
return $args;
} );
function wpse_get_terms( $terms, $taxonomies, $args )
{
if( isset( $taxonomies[0] )
&& 'schedule_day_taxonomy' === $taxonomies[0]
&& 'schedule' === get_current_screen()->id
) {
$newterms = [];
foreach( (array) $GLOBALS['wp_locale']->weekday as $day )
{
foreach( (array) $terms as $term )
{
if( $term->name === $day )
$newterms[] = $term;
}
}
remove_filter( current_filter(), __FUNCTION__ );
if( 7 === count( $newterms ) )
$terms = $newterms;
}
return $terms;
}
```
We could also replace
```
$GLOBALS['wp_locale']->weekday
```
with a custom weekdays array, ordered in a custom way.
Here's the *English* version:
[](https://i.stack.imgur.com/S1YYp.jpg)
and here's the *Icelandic* version:
[](https://i.stack.imgur.com/BYtjD.jpg)
Method #3 - Custom SQL ordering
-------------------------------
We could modify the SQL ordering with the `get_terms_orderby` filter, with a `CASE/WHEN/THEN` setup.
Hopefully you can adjust this to your needs.
|
202,173 |
<p>I am trying to replace the categories metabox with what looks and works like the tags metabox because there's too much hierarchy and scrolling to check the appropriate categories and sub-categories isn't an option. So in my case tags'-like metabox is better.</p>
<p>This is how I am doing it:</p>
<pre><code>/*
* Non-hierarchal metabox for categories
* (like the tags metabox)
*
* SOURCES:
* http://wordpress.stackexchange.com/a/50098
* http://wordpress.stackexchange.com/a/49048
* http://wordpress.stackexchange.com/a/48816
*
*/
// De-register categories metabox
add_action( 'admin_menu', 'flatsy_remove_meta_box' );
function flatsy_remove_meta_box() {
remove_meta_box( 'categorydiv', 'post', 'normal' );
}
// Add new taxonomy meta box
add_action( 'add_meta_boxes', 'flatsy_add_custom_cat_meta_box' );
function flatsy_add_custom_cat_meta_box() {
add_meta_box( 'flatsy_categorydiv', 'Categories', 'flatsy_custom_cat_metabox', 'post', 'side', 'core' );
}
// This function determines what displays in your metabox
function flatsy_custom_cat_metabox( $post ) {
$defaults = array('taxonomy' => 'category');
if ( !isset($box['args']) || !is_array($box['args']) )
$args = array();
else
$args = $box['args'];
extract( wp_parse_args($args, $defaults), EXTR_SKIP );
$tax_name = esc_attr($taxonomy);
$taxonomy = get_taxonomy($taxonomy);
$disabled = !current_user_can($taxonomy->cap->assign_terms) ? 'disabled="disabled"' : '';
?>
<div class="tagsdiv" id="<?php echo $tax_name; ?>">
<div class="jaxtag">
<div class="nojs-tags hide-if-js">
<p><?php echo $taxonomy->labels->add_or_remove_items; ?></p>
<textarea name="<?php echo "tax_input[$tax_name]"; ?>" rows="3" cols="20" class="the-tags" id="tax-input-<?php echo $tax_name; ?>" <?php echo $disabled; ?>><?php echo get_terms_to_edit( $post->ID, $tax_name ); // textarea_escaped by esc_attr() ?></textarea></div>
<?php if ( current_user_can($taxonomy->cap->assign_terms) ) : ?>
<div class="ajaxtag hide-if-no-js">
<label class="screen-reader-text" for="new-tag-<?php echo $tax_name; ?>"><?php echo $box['title']; ?></label>
<div class="taghint"><?php echo $taxonomy->labels->add_new_item; ?></div>
<p><input type="text" id="new-tag-<?php echo $tax_name; ?>" name="newtag[<?php echo $tax_name; ?>]" class="newtag form-input-tip" size="16" autocomplete="off" value="" />
<input type="button" class="button tagadd" value="<?php esc_attr_e('Add'); ?>" tabindex="3" /></p>
</div>
<p class="howto"><?php echo esc_attr( $taxonomy->labels->separate_items_with_commas ); ?></p>
<?php endif; ?>
</div>
<div class="tagchecklist"></div>
</div>
<?php if ( current_user_can($taxonomy->cap->assign_terms) ) : ?>
<p class="hide-if-no-js"><a href="#titlediv" class="tagcloud-link" id="link-<?php echo $tax_name; ?>"><?php echo $taxonomy->labels->choose_from_most_used; ?></a></p>
<?php endif; ?>
<?php
}
</code></pre>
<p>That piece of code works as it should... see...</p>
<p><a href="https://i.stack.imgur.com/nFtvN.png" rel="nofollow noreferrer" title="The categories metabox now looks like the tags metabox"><img src="https://i.stack.imgur.com/nFtvN.png" alt="The categories metabox now looks like the tags metabox" title="The categories metabox now looks like the tags metabox"></a></p>
<p><strong>...except</strong> that it isn't saving the category metadata when the post is saved. A little bit of searching revealed that I must be doing something <a href="http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336" rel="nofollow noreferrer">like this</a>:</p>
<pre><code><?php
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchors can only have href attribute
)
);
// Make sure your data is set before trying to save it
if( isset( $_POST['my_meta_box_text'] ) )
update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
if( isset( $_POST['my_meta_box_select'] ) )
update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) );
// This is purely my personal preference for saving check-boxes
$chk = isset( $_POST['my_meta_box_check'] ) && $_POST['my_meta_box_select'] ? 'on' : 'off';
update_post_meta( $post_id, 'my_meta_box_check', $chk );
}
?>
</code></pre>
<p>But as I am dealing with the default functionality (i.e. how/what wordpress already does with tags metabox), <strong>I want to know what checks are in place for <code>save_post</code> for 'category' and 'tag' meta boxes and how WordPress does it by default.</strong></p>
<pre><code>// Save post metadata when a post is saved.
add_action( 'save_post', 'flatsy_save_cat_meta' );
function flatsy_save_cat_meta( $post_id, $post, $update ) {
return 'WHAT DO I DO HERE? HOW DOES WORDPRESS DO IT FOR THE TAGS METABOX?';
}
</code></pre>
<p><strong>AND if that's not how it's done, what should the code look like when I am converting the category metabox to look like a tag metabox and vice-versa (two cases)?</strong></p>
<hr>
<p><strong>CLARIFICATION:</strong> I don't want to change Categories from hierarchical to non-hierarchical. I just want a tags-like metabox for categories. If I wanted a non-hierarchical taxonomy I'd simply have registered a custom taxonomy.</p>
|
[
{
"answer_id": 202452,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>How do the 'tag' and 'category' (default) taxonomies do 'save_post' action?</p>\n</blockquote>\n\n<p>They don't!</p>\n\n<p>Taxonomies aren't handled with a <code>save_post</code> action, it all happens directly inside <code>wp_insert_post</code>. <a href=\"https://core.trac.wordpress.org/browser/tags/4.3/src/wp-includes/post.php#L3460\" rel=\"nofollow\">You can see it in source here</a>.</p>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow\"><code>wp_set_object_terms</code></a> in your callback to save terms from your custom metabox.</p>\n"
},
{
"answer_id": 202466,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>It's informative to check out the <code>/wp-admin/post.php</code> file, that contains the <code>edit_post()</code> function that calls <code>wp_update_post()</code>, which is a <code>wp_insert_post()</code> wrapper.</p>\n\n<p>Here's a skeleton for saving the assigned category terms:</p>\n\n<pre><code>/**\n * Saving assigned category terms (skeleton)\n */\nadd_action( 'admin_action_editpost', function()\n{\n add_filter( 'wp_insert_post_data', function( $data, $parr )\n {\n add_action( 'save_post_post', function( $post_ID, $post ) use ( $parr )\n {\n if( \n isset( $parr['_wpnonce'] )\n && wp_verify_nonce( $parr['_wpnonce'], 'update-post_' . absint( $post_ID ) )\n && current_user_can( 'manage_categories' )\n && function_exists( 'wpse_save_assigned_cats' )\n && ! did_action( 'wpse_save_assigned_cats' )\n ) {\n wpse_save_assigned_cats( $post_ID, $parr );\n do_action( 'wpse_save_assigned_cats' );\n }\n }, 10, 2 );\n return $data;\n }, 10, 2 );\n} );\n</code></pre>\n\n<p>where our helper function <code>wpse_save_assigned_cats()</code> is based on the <code>edit_post()</code> function:</p>\n\n<pre><code>/**\n * Helper function based on the cat/tax handling of the edit_post() functions\n */\nfunction wpse_save_assigned_cats( $post_ID, $parr )\n{\n if( ! empty( $parr['tax_input']['category'] ) && $post_ID > 0 )\n { \n // Change the comma seperated string of category names,\n // in $parr['tax_input']['category'], to an array of cats id\n $input_cats = explode( ',', trim( $parr['tax_input']['category'], \" \\n\\t\\r\\0\\x0B,\" ) );\n $clean_cats = array();\n foreach ( $input_cats as $cat_name )\n {\n // Don't allow empty categories\n if ( empty( $cat_name ) )\n continue;\n\n // Check if there already exists such a category\n $_cat = get_terms( 'category', array(\n 'name' => $cat_name,\n 'fields' => 'ids',\n 'hide_empty' => false,\n ) ); \n\n // The category name already exists\n if ( ! empty( $_cat ) )\n {\n // Collect the (first) category id\n $clean_cats[] = intval( $_cat[0] );\n } \n else \n {\n // Create the category, since it doesn't exists\n $cat_id = wp_create_category( $cat_name );\n\n // Collect the category id\n if( $cat_id > 0 )\n $clean_cats[] = $cat_id;\n }\n }\n // Current post's category IDs\n $cats = (array) wp_get_post_categories( $post_ID, array( 'fields' => 'ids' ) );\n\n // Unique array of category IDs\n $post_categories = array_unique( array_merge( $cats, $clean_cats ) ); \n\n // Assign the categories to the current post \n wp_set_post_categories( $post_ID, $post_categories );\n } \n}\n</code></pre>\n\n<h2>Previous Answer:</h2>\n\n<p>Here's my Friday answer, so it might need some testing ;-)</p>\n\n<p>I just re-registered the <code>category</code> taxonomy as <em>non-hierarchical</em> with: </p>\n\n<pre><code> 'hierarchical' => false,\n</code></pre>\n\n<p>Then the category box showed up like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JgAEC.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JgAEC.jpg\" alt=\"category\"></a></p>\n\n<p>and saving terms worked as expected.</p>\n\n<p>Here's my testing code snippet, so you can try it further:</p>\n\n<pre><code>add_action( 'init', function()\n{\n global $wp_rewrite;\n register_taxonomy( 'category', 'post', array(\n 'hierarchical' => false,\n 'query_var' => 'category_name',\n 'rewrite' => array(\n 'hierarchical' => true,\n 'slug' => get_option('category_base') ? get_option('category_base') : 'category',\n 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),\n 'ep_mask' => EP_CATEGORIES,\n ),\n 'public' => true,\n 'show_ui' => true,\n 'show_admin_column' => true,\n '_builtin' => true,\n 'labels' => array(\n 'name' => __( 'Categories' ),\n 'singular_name' => __( 'Category' ),\n 'search_items' => __( 'Search Categories' ),\n 'popular_items' => null,\n 'all_items' => __( 'All Categories' ),\n 'edit_item' => __( 'Edit Category' ),\n 'update_item' => __( 'Update Category' ),\n 'add_new_item' => __( 'Add New Category' ),\n 'new_item_name' => __( 'New Category Name' ),\n 'separate_items_with_commas' => null,\n 'add_or_remove_items' => null,\n 'choose_from_most_used' => null,\n ),\n 'capabilities' => array(\n 'manage_terms' => 'manage_categories',\n 'edit_terms' => 'manage_categories',\n 'delete_terms' => 'manage_categories',\n 'assign_terms' => 'edit_posts',\n ),\n ) );\n} );\n</code></pre>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202173",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10691/"
] |
I am trying to replace the categories metabox with what looks and works like the tags metabox because there's too much hierarchy and scrolling to check the appropriate categories and sub-categories isn't an option. So in my case tags'-like metabox is better.
This is how I am doing it:
```
/*
* Non-hierarchal metabox for categories
* (like the tags metabox)
*
* SOURCES:
* http://wordpress.stackexchange.com/a/50098
* http://wordpress.stackexchange.com/a/49048
* http://wordpress.stackexchange.com/a/48816
*
*/
// De-register categories metabox
add_action( 'admin_menu', 'flatsy_remove_meta_box' );
function flatsy_remove_meta_box() {
remove_meta_box( 'categorydiv', 'post', 'normal' );
}
// Add new taxonomy meta box
add_action( 'add_meta_boxes', 'flatsy_add_custom_cat_meta_box' );
function flatsy_add_custom_cat_meta_box() {
add_meta_box( 'flatsy_categorydiv', 'Categories', 'flatsy_custom_cat_metabox', 'post', 'side', 'core' );
}
// This function determines what displays in your metabox
function flatsy_custom_cat_metabox( $post ) {
$defaults = array('taxonomy' => 'category');
if ( !isset($box['args']) || !is_array($box['args']) )
$args = array();
else
$args = $box['args'];
extract( wp_parse_args($args, $defaults), EXTR_SKIP );
$tax_name = esc_attr($taxonomy);
$taxonomy = get_taxonomy($taxonomy);
$disabled = !current_user_can($taxonomy->cap->assign_terms) ? 'disabled="disabled"' : '';
?>
<div class="tagsdiv" id="<?php echo $tax_name; ?>">
<div class="jaxtag">
<div class="nojs-tags hide-if-js">
<p><?php echo $taxonomy->labels->add_or_remove_items; ?></p>
<textarea name="<?php echo "tax_input[$tax_name]"; ?>" rows="3" cols="20" class="the-tags" id="tax-input-<?php echo $tax_name; ?>" <?php echo $disabled; ?>><?php echo get_terms_to_edit( $post->ID, $tax_name ); // textarea_escaped by esc_attr() ?></textarea></div>
<?php if ( current_user_can($taxonomy->cap->assign_terms) ) : ?>
<div class="ajaxtag hide-if-no-js">
<label class="screen-reader-text" for="new-tag-<?php echo $tax_name; ?>"><?php echo $box['title']; ?></label>
<div class="taghint"><?php echo $taxonomy->labels->add_new_item; ?></div>
<p><input type="text" id="new-tag-<?php echo $tax_name; ?>" name="newtag[<?php echo $tax_name; ?>]" class="newtag form-input-tip" size="16" autocomplete="off" value="" />
<input type="button" class="button tagadd" value="<?php esc_attr_e('Add'); ?>" tabindex="3" /></p>
</div>
<p class="howto"><?php echo esc_attr( $taxonomy->labels->separate_items_with_commas ); ?></p>
<?php endif; ?>
</div>
<div class="tagchecklist"></div>
</div>
<?php if ( current_user_can($taxonomy->cap->assign_terms) ) : ?>
<p class="hide-if-no-js"><a href="#titlediv" class="tagcloud-link" id="link-<?php echo $tax_name; ?>"><?php echo $taxonomy->labels->choose_from_most_used; ?></a></p>
<?php endif; ?>
<?php
}
```
That piece of code works as it should... see...
[](https://i.stack.imgur.com/nFtvN.png "The categories metabox now looks like the tags metabox")
**...except** that it isn't saving the category metadata when the post is saved. A little bit of searching revealed that I must be doing something [like this](http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336):
```
<?php
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchors can only have href attribute
)
);
// Make sure your data is set before trying to save it
if( isset( $_POST['my_meta_box_text'] ) )
update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
if( isset( $_POST['my_meta_box_select'] ) )
update_post_meta( $post_id, 'my_meta_box_select', esc_attr( $_POST['my_meta_box_select'] ) );
// This is purely my personal preference for saving check-boxes
$chk = isset( $_POST['my_meta_box_check'] ) && $_POST['my_meta_box_select'] ? 'on' : 'off';
update_post_meta( $post_id, 'my_meta_box_check', $chk );
}
?>
```
But as I am dealing with the default functionality (i.e. how/what wordpress already does with tags metabox), **I want to know what checks are in place for `save_post` for 'category' and 'tag' meta boxes and how WordPress does it by default.**
```
// Save post metadata when a post is saved.
add_action( 'save_post', 'flatsy_save_cat_meta' );
function flatsy_save_cat_meta( $post_id, $post, $update ) {
return 'WHAT DO I DO HERE? HOW DOES WORDPRESS DO IT FOR THE TAGS METABOX?';
}
```
**AND if that's not how it's done, what should the code look like when I am converting the category metabox to look like a tag metabox and vice-versa (two cases)?**
---
**CLARIFICATION:** I don't want to change Categories from hierarchical to non-hierarchical. I just want a tags-like metabox for categories. If I wanted a non-hierarchical taxonomy I'd simply have registered a custom taxonomy.
|
It's informative to check out the `/wp-admin/post.php` file, that contains the `edit_post()` function that calls `wp_update_post()`, which is a `wp_insert_post()` wrapper.
Here's a skeleton for saving the assigned category terms:
```
/**
* Saving assigned category terms (skeleton)
*/
add_action( 'admin_action_editpost', function()
{
add_filter( 'wp_insert_post_data', function( $data, $parr )
{
add_action( 'save_post_post', function( $post_ID, $post ) use ( $parr )
{
if(
isset( $parr['_wpnonce'] )
&& wp_verify_nonce( $parr['_wpnonce'], 'update-post_' . absint( $post_ID ) )
&& current_user_can( 'manage_categories' )
&& function_exists( 'wpse_save_assigned_cats' )
&& ! did_action( 'wpse_save_assigned_cats' )
) {
wpse_save_assigned_cats( $post_ID, $parr );
do_action( 'wpse_save_assigned_cats' );
}
}, 10, 2 );
return $data;
}, 10, 2 );
} );
```
where our helper function `wpse_save_assigned_cats()` is based on the `edit_post()` function:
```
/**
* Helper function based on the cat/tax handling of the edit_post() functions
*/
function wpse_save_assigned_cats( $post_ID, $parr )
{
if( ! empty( $parr['tax_input']['category'] ) && $post_ID > 0 )
{
// Change the comma seperated string of category names,
// in $parr['tax_input']['category'], to an array of cats id
$input_cats = explode( ',', trim( $parr['tax_input']['category'], " \n\t\r\0\x0B," ) );
$clean_cats = array();
foreach ( $input_cats as $cat_name )
{
// Don't allow empty categories
if ( empty( $cat_name ) )
continue;
// Check if there already exists such a category
$_cat = get_terms( 'category', array(
'name' => $cat_name,
'fields' => 'ids',
'hide_empty' => false,
) );
// The category name already exists
if ( ! empty( $_cat ) )
{
// Collect the (first) category id
$clean_cats[] = intval( $_cat[0] );
}
else
{
// Create the category, since it doesn't exists
$cat_id = wp_create_category( $cat_name );
// Collect the category id
if( $cat_id > 0 )
$clean_cats[] = $cat_id;
}
}
// Current post's category IDs
$cats = (array) wp_get_post_categories( $post_ID, array( 'fields' => 'ids' ) );
// Unique array of category IDs
$post_categories = array_unique( array_merge( $cats, $clean_cats ) );
// Assign the categories to the current post
wp_set_post_categories( $post_ID, $post_categories );
}
}
```
Previous Answer:
----------------
Here's my Friday answer, so it might need some testing ;-)
I just re-registered the `category` taxonomy as *non-hierarchical* with:
```
'hierarchical' => false,
```
Then the category box showed up like this:
[](https://i.stack.imgur.com/JgAEC.jpg)
and saving terms worked as expected.
Here's my testing code snippet, so you can try it further:
```
add_action( 'init', function()
{
global $wp_rewrite;
register_taxonomy( 'category', 'post', array(
'hierarchical' => false,
'query_var' => 'category_name',
'rewrite' => array(
'hierarchical' => true,
'slug' => get_option('category_base') ? get_option('category_base') : 'category',
'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
'ep_mask' => EP_CATEGORIES,
),
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'_builtin' => true,
'labels' => array(
'name' => __( 'Categories' ),
'singular_name' => __( 'Category' ),
'search_items' => __( 'Search Categories' ),
'popular_items' => null,
'all_items' => __( 'All Categories' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category Name' ),
'separate_items_with_commas' => null,
'add_or_remove_items' => null,
'choose_from_most_used' => null,
),
'capabilities' => array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_posts',
),
) );
} );
```
|
202,188 |
<p>I have created custom post type <code>gallery</code>. </p>
<p>How change the <code>previous post</code> and <code>next post</code> link to point to the current Authors posts only?</p>
<p>The Previous and Next Post link should not display if there are no more posts</p>
<p><a href="https://i.stack.imgur.com/Z4tQ2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z4tQ2.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 202292,
"author": "Shahrukh Khan",
"author_id": 67596,
"author_profile": "https://wordpress.stackexchange.com/users/67596",
"pm_score": -1,
"selected": true,
"text": "<p>To limit post navigation to the same author and category, locate the link-template.php file in the /wp-includes/ folder, and edit using your favorite text editor (Notepad++ for me). In this file you will alter four functions. Locate the following lines in the link-template.php file:</p>\n\n<pre><code>function previous_post_link($format='&laquo; %link', $link='%title', $in_same_cat = false, $excluded_categories = '') {\n adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true);\n}\n</code></pre>\n\n<p>Change that to the following:</p>\n\n<pre><code>function previous_post_link($format='&laquo; %link', $link='%title', $in_same_cat = false, $excluded_categories = '', $is_author = false) {\n adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true, $is_author);\n}\n</code></pre>\n\n<p>Below the previous lines of code you should find this:</p>\n\n<pre><code>function next_post_link($format='%link &raquo;', $link='%title', $in_same_cat = false, $excluded_categories = '') {\n adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);\n}\n</code></pre>\n\n<p>Change that to the following:</p>\n\n<pre><code>function next_post_link($format='%link &raquo;', $link='%title', $in_same_cat = false, $excluded_categories = '',$is_author = false) {\n adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false, $is_author);\n}\n</code></pre>\n\n<p>These changes are small. You should notice that the only changes made were adding $is_author = false to the function parameters and $is_author to the call to adjacent_post_link call.</p>\n\n<p>On the next function you'll be adding another parameter and adjust the SELECT query that is pulling in the next/previous post. Locate the following line that should look something like this:</p>\n\n<pre><code>function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true) {\n ...\n }\n</code></pre>\n\n<p>This block is fairly long so I'm only covering what's being changed. On this line add the same parameter as before ($is_author = false):</p>\n\n<pre><code>function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true, $is_author = false) {\n ...\n }\n</code></pre>\n\n<p>Next, in this same function find the $where variable as shown below (roughly 50 lines into the function).</p>\n\n<pre><code>$where = apply_filters( \"get_{$adjacent}_post_where\", $wpdb->prepare(\"WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql\", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories );\n</code></pre>\n\n<p>What we want to do next is alter this variable so it retains the author only when $is_author is true. To do this test the boolean value of $is_author and tack a little extra on the end of the $where variable.</p>\n\n<pre><code>$where = apply_filters( \"get_{$adjacent}_post_where\", $wpdb->prepare(\"WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql\", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories );\n if($is_author)\n $where .= \" AND p.post_author='\".$post->post_author.\"'\";\n</code></pre>\n\n<p>For the final change in the link-template.php file locate the following function:</p>\n\n<pre><code>function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {\n if ( $previous && is_attachment() )\n $post = & get_post($GLOBALS['post']->post_parent);\n else\n $post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);\n</code></pre>\n\n<p>Alter this function by the $is_author in the adjacent_post_link function and adding it to the get_adjacent_post call:</p>\n\n<pre><code>function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true, $is_author = false) {\n if ( $previous && is_attachment() )\n $post = & get_post($GLOBALS['post']->post_parent);\n else\n $post = get_adjacent_post($in_same_cat, $excluded_categories, $previous, $is_author);\n</code></pre>\n\n<p>Now you're ready to use this new option in the theme files. To \"activate\" the retain author function use something like this in your single.php:</p>\n\n<pre><code><?php previous_post_link( '%link', '' . _x( '&larr;', 'Previous post link', 'twentyten' ) . ' %title','true','','true' ); ?>\n<?php next_post_link( '%link', '%title ' . _x( '&rarr;', 'Next post link', 'twentyten' ) . '','true','','true' ); ?>\n</code></pre>\n\n<p>Setting the last value to \"true\" activates the retain author function for that link. This will ensure the link stays within the same author as well as the same date. </p>\n"
},
{
"answer_id": 228867,
"author": "Cin",
"author_id": 92387,
"author_profile": "https://wordpress.stackexchange.com/users/92387",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>correct</strong> method of doing this since Wordpress 4.4 is simply the following:</p>\n\n<pre><code>add_filter( \"get_next_post_where\", function($where, $in_same_term, $excluded_terms, $taxonomy, $post){\n $where .= \" AND p.post_author='\".$post->post_author.\"'\";\n return $where;\n}, 10, 5);\n\nadd_filter( \"get_previous_post_where\", function($where, $in_same_term, $excluded_terms, $taxonomy, $post){\n $where .= \" AND p.post_author='\".$post->post_author.\"'\";\n return $where;\n}, 10, 5);\n</code></pre>\n\n<p><strong>Note:</strong> Please do not follow levidia1221's accepted response, as it involves modifying Wordpress Core, which is a terrible idea. Modifying the core means you can't update Wordpress without losing your changes, which is an enormous security risk. If there are no hooks present in a function you want to modify, it's better to copy the functions you need and change them in your theme or plugin, rather than modifying the core files directly.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202188",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
I have created custom post type `gallery`.
How change the `previous post` and `next post` link to point to the current Authors posts only?
The Previous and Next Post link should not display if there are no more posts
[](https://i.stack.imgur.com/Z4tQ2.png)
|
To limit post navigation to the same author and category, locate the link-template.php file in the /wp-includes/ folder, and edit using your favorite text editor (Notepad++ for me). In this file you will alter four functions. Locate the following lines in the link-template.php file:
```
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true);
}
```
Change that to the following:
```
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '', $is_author = false) {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true, $is_author);
}
```
Below the previous lines of code you should find this:
```
function next_post_link($format='%link »', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);
}
```
Change that to the following:
```
function next_post_link($format='%link »', $link='%title', $in_same_cat = false, $excluded_categories = '',$is_author = false) {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false, $is_author);
}
```
These changes are small. You should notice that the only changes made were adding $is\_author = false to the function parameters and $is\_author to the call to adjacent\_post\_link call.
On the next function you'll be adding another parameter and adjust the SELECT query that is pulling in the next/previous post. Locate the following line that should look something like this:
```
function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true) {
...
}
```
This block is fairly long so I'm only covering what's being changed. On this line add the same parameter as before ($is\_author = false):
```
function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true, $is_author = false) {
...
}
```
Next, in this same function find the $where variable as shown below (roughly 50 lines into the function).
```
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories );
```
What we want to do next is alter this variable so it retains the author only when $is\_author is true. To do this test the boolean value of $is\_author and tack a little extra on the end of the $where variable.
```
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories );
if($is_author)
$where .= " AND p.post_author='".$post->post_author."'";
```
For the final change in the link-template.php file locate the following function:
```
function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
```
Alter this function by the $is\_author in the adjacent\_post\_link function and adding it to the get\_adjacent\_post call:
```
function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true, $is_author = false) {
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous, $is_author);
```
Now you're ready to use this new option in the theme files. To "activate" the retain author function use something like this in your single.php:
```
<?php previous_post_link( '%link', '' . _x( '←', 'Previous post link', 'twentyten' ) . ' %title','true','','true' ); ?>
<?php next_post_link( '%link', '%title ' . _x( '→', 'Next post link', 'twentyten' ) . '','true','','true' ); ?>
```
Setting the last value to "true" activates the retain author function for that link. This will ensure the link stays within the same author as well as the same date.
|
202,200 |
<p>I have some dynamic templates where I have to customize the canonical links. </p>
<p>According to Yoast documentation the hook to use is <code>wpseo_canonical</code></p>
<p>I have two functions pointing to different pages IDs:</p>
<pre><code>add_filter('wpseo_canonical', 'listpagecanonical');
function listpagecanonical($string) {
if (is_page(1)){
//I do my stuff here
return 'http://canonicalurl.com'
}
}
</code></pre>
<p>Then I have another:</p>
<pre><code>add_filter('wpseo_canonical', 'detailpagecanonical');
function detailpagecanonical($string) {
if (is_page(2)){
//I do my stuff here
return 'http://canonicalurl2.com'
}
}
</code></pre>
<p>The problem I'm having is that if both filters have the same priority, like the example, they simply don't work, if I add 10, 1 to the first it will work but 2nd wont. If I add 20, 1 to second, it will work but first will stop working and so on.</p>
<p>Is there any way to do this in a way that they don't override themselves like that?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 202202,
"author": "Max",
"author_id": 78380,
"author_profile": "https://wordpress.stackexchange.com/users/78380",
"pm_score": 3,
"selected": true,
"text": "<p>Filters should be returned even if your condition fails. You are currently just returning the output when your condition is met, not when it fails.</p>\n\n<p><code>return $string;</code> at the end of each function should solve your issue.</p>\n\n<h2>EXAMPLE</h2>\n\n<pre><code>add_filter('wpseo_canonical', 'listpagecanonical');\nfunction listpagecanonical($string) {\n if (is_page(1)){\n //I do my stuff here\n return 'http://canonicalurl.com'\n }\n return $string;\n}\n</code></pre>\n"
},
{
"answer_id": 202204,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is that in filter you should always return a value. If you don't have to change the value being passed, then you should return it.</p>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202200",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15574/"
] |
I have some dynamic templates where I have to customize the canonical links.
According to Yoast documentation the hook to use is `wpseo_canonical`
I have two functions pointing to different pages IDs:
```
add_filter('wpseo_canonical', 'listpagecanonical');
function listpagecanonical($string) {
if (is_page(1)){
//I do my stuff here
return 'http://canonicalurl.com'
}
}
```
Then I have another:
```
add_filter('wpseo_canonical', 'detailpagecanonical');
function detailpagecanonical($string) {
if (is_page(2)){
//I do my stuff here
return 'http://canonicalurl2.com'
}
}
```
The problem I'm having is that if both filters have the same priority, like the example, they simply don't work, if I add 10, 1 to the first it will work but 2nd wont. If I add 20, 1 to second, it will work but first will stop working and so on.
Is there any way to do this in a way that they don't override themselves like that?
Thanks.
|
Filters should be returned even if your condition fails. You are currently just returning the output when your condition is met, not when it fails.
`return $string;` at the end of each function should solve your issue.
EXAMPLE
-------
```
add_filter('wpseo_canonical', 'listpagecanonical');
function listpagecanonical($string) {
if (is_page(1)){
//I do my stuff here
return 'http://canonicalurl.com'
}
return $string;
}
```
|
202,220 |
<p>I have tried using <code>sanitize_text_field()</code> and <code>esc_attr()</code> to filter checkbox data when saving their values to the database, but it is causing the data not being saved.</p>
<p>What is causing it and what's the correct way to filter input <code>checkbox</code> and <code>radio</code>?</p>
|
[
{
"answer_id": 202222,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 1,
"selected": false,
"text": "<p>I mean that the value of checkbox or radio is often a integer value. If is a integer value, then set it to a integer as solid filter. </p>\n\n<p><code>$checkbox = (int) $checkbox;</code></p>\n\n<p>If you use strings on the radio items, then use <code>esc_attr</code> to filter solid. The function <code>sanitize_text_field</code> have also a filter, that other plugins can change the output, maybe not helpful for your goal. THe function is more for filter input from users or from database. <code>esc_attr</code>have also a filter, but is more solid for your requirements.</p>\n\n<p>More information you can find on the <a href=\"http://codex.wordpress.org/Data_Validation\" rel=\"nofollow\">codex page about validation</a>.</p>\n"
},
{
"answer_id": 202223,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 3,
"selected": true,
"text": "<p>I would use the filter_var() function. It has some predefined filters that you can use depending on what kind of data you are expecting such as string, number, etc.</p>\n\n<p>So to sanitize for a number:</p>\n\n<pre><code>$sanitizedNum = filter_var($yourVar, FILTER_SANITIZE_NUMBER_INT);\n</code></pre>\n\n<p>For a string you would just change \"_NUM_INT\" to \"_STRING\".</p>\n\n<p>Wrap those in a custom function then.</p>\n"
},
{
"answer_id": 306851,
"author": "Md. Abunaser Khan",
"author_id": 103030,
"author_profile": "https://wordpress.stackexchange.com/users/103030",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I have use this function it working.</strong> </p>\n\n<pre><code>/************************************************************************\n************** How to sanitize checkbox*************************\n************************************************************************/\n\n\nfunction theme_slug_customizer( $wp_customize ) { \n\n //your section\n $wp_customize->add_section( \n 'theme_slug_customizer_your_section', \n array(\n 'title' => esc_html__( 'Your Section', 'theme_slug' ),\n 'priority' => 150\n )\n ); \n\n\n //checkbox sanitization function\n function theme_slug_sanitize_checkbox( $input ){\n\n //returns true if checkbox is checked\n return ( isset( $input ) ? true : false );\n }\n\n\n //add setting to your section\n $wp_customize->add_setting( \n 'theme_slug_customizer_checkbox', \n array(\n 'default' => '',\n 'sanitize_callback' => 'theme_slug_sanitize_checkbox'\n )\n );\n\n $wp_customize->add_control( \n 'theme_slug_customizer_checkbox', \n array(\n 'label' => esc_html__( 'Your Setting with Checkbox', 'theme_slug' ),\n 'section' => 'theme_slug_customizer_your_section',\n 'type' => 'checkbox'\n )\n ); \n\n}\nadd_action( 'customize_register', 'theme_slug_customizer' );\n\n\n\n\n\n\n\n\n\n\n/************************************************************************\n************** How to sanitize radio box *************************\n************************************************************************/\n\n\nfunction theme_slug_customizer( $wp_customize ) { \n\n //your section\n $wp_customize->add_section( \n 'theme_slug_customizer_your_section', \n array(\n 'title' => esc_html__( 'Your Section', 'theme_slug' ),\n 'priority' => 150\n )\n ); \n\n\n //radio box sanitization function\n function theme_slug_sanitize_radio( $input, $setting ){\n\n //input must be a slug: lowercase alphanumeric characters, dashes and underscores are allowed only\n $input = sanitize_key($input);\n\n //get the list of possible radio box options \n $choices = $setting->manager->get_control( $setting->id )->choices;\n\n //return input if valid or return default option\n return ( array_key_exists( $input, $choices ) ? $input : $setting->default ); \n\n }\n\n\n //add setting to your section\n $wp_customize->add_setting( \n 'theme_slug_customizer_radio', \n array(\n 'sanitize_callback' => 'theme_slug_sanitize_radio'\n )\n );\n\n $wp_customize->add_control( \n 'theme_slug_customizer_radio', \n array(\n 'label' => esc_html__( 'Your Setting with Radio Box', 'theme_slug' ),\n 'section' => 'theme_slug_customizer_your_section',\n 'type' => 'radio',\n 'choices' => array(\n 'one' => esc_html__('Choice One','theme_slug'),\n 'two' => esc_html__('Choice Two','theme_slug'),\n 'three' => esc_html__('Choice Three','theme_slug') \n )\n )\n ); \n\n}\nadd_action( 'customize_register', 'theme_slug_customizer' );\n</code></pre>\n"
}
] |
2015/09/09
|
[
"https://wordpress.stackexchange.com/questions/202220",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32989/"
] |
I have tried using `sanitize_text_field()` and `esc_attr()` to filter checkbox data when saving their values to the database, but it is causing the data not being saved.
What is causing it and what's the correct way to filter input `checkbox` and `radio`?
|
I would use the filter\_var() function. It has some predefined filters that you can use depending on what kind of data you are expecting such as string, number, etc.
So to sanitize for a number:
```
$sanitizedNum = filter_var($yourVar, FILTER_SANITIZE_NUMBER_INT);
```
For a string you would just change "\_NUM\_INT" to "\_STRING".
Wrap those in a custom function then.
|
202,252 |
<p>I'd like to display the post author's name and avatar on posts sidebar but I can't find any info on it.</p>
<p>Is there a shortcode or piece of code to do this ? </p>
<p>Thanks for your help</p>
|
[
{
"answer_id": 202255,
"author": "Tech9logy Creators",
"author_id": 75410,
"author_profile": "https://wordpress.stackexchange.com/users/75410",
"pm_score": 0,
"selected": false,
"text": "<p>if you are using it in <a href=\"http://codex.wordpress.org/The_Loop\" rel=\"nofollow\">Loop</a> then :</p>\n\n<p>You can display author name by using </p>\n\n<pre><code><?php $author = get_the_author();\n echo $author; ?>\n</code></pre>\n\n<p>and you can display post author avatar using </p>\n\n<pre><code><?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>\n</code></pre>\n\n<p>you can change 32 size to whatever your need.</p>\n\n<p>Hope this will work for you.</p>\n\n<p>thanks</p>\n"
},
{
"answer_id": 259599,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>Display author's name and avatar in Post page and single post page sidebar.\nPut this code in sidebar.php</p>\n\n<pre><code> if(is_home() || is_single()){\n echo get_avatar( $post->post_author,'100');\n echo get_the_author($post->post_author);\n }\n</code></pre>\n\n<p>I hope useful.</p>\n"
},
{
"answer_id": 272837,
"author": "Vijay Baria",
"author_id": 117023,
"author_profile": "https://wordpress.stackexchange.com/users/117023",
"pm_score": 2,
"selected": false,
"text": "<p>Display author's avatar and name in single page sidebar. Add this code in sidebar.php or single.php</p>\n\n<pre><code>if ( is_singular( 'post' ) ) {\n echo get_avatar( get_the_author_meta( 'user_email' ), 75 );\n echo get_the_author_meta( 'display_name' );\n}\n</code></pre>\n\n<p>Here 75 number is the avatar size.</p>\n\n<p>I hope it will help you.</p>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202252",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68671/"
] |
I'd like to display the post author's name and avatar on posts sidebar but I can't find any info on it.
Is there a shortcode or piece of code to do this ?
Thanks for your help
|
Display author's avatar and name in single page sidebar. Add this code in sidebar.php or single.php
```
if ( is_singular( 'post' ) ) {
echo get_avatar( get_the_author_meta( 'user_email' ), 75 );
echo get_the_author_meta( 'display_name' );
}
```
Here 75 number is the avatar size.
I hope it will help you.
|
202,260 |
<p>I am trying to add a function to my child theme to append the currently logged user as a parameter. For example, when the user test1 logs in and clicks on the following page:</p>
<pre><code>http://www.example.com/my-wishlist
</code></pre>
<p>I want her to be redirected automatically to </p>
<pre><code>http://www.example.com/my-wishlist/?user=test1
</code></pre>
<p>So far I did the following but it ends in a loop:</p>
<pre><code>$current_user = wp_get_current_user();
if ( is_user_logged_in() ) {
wp_redirect( 'http://www.example.com/my-wishlist/?user='.$current_user->user_login );
exit;
}
</code></pre>
<p>I would appreciate some help. Thank you</p>
|
[
{
"answer_id": 202263,
"author": "jzatt",
"author_id": 22620,
"author_profile": "https://wordpress.stackexchange.com/users/22620",
"pm_score": 0,
"selected": false,
"text": "<p>You are getting the redirect loop because your script isn't checking if the user already is redirected.</p>\n\n<p>Try adding another condition to your <code>if</code> to check for the user variable...</p>\n\n<pre><code>$current_user = wp_get_current_user(); \nif ( is_user_logged_in() && !isset( $_GET['user'] ) ) {\n wp_redirect( 'http://www.example.com/my-wishlist/?user='.$current_user->user_login ); \n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 202285,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow\">add_query_arg</a> to make sure the url is created the right way. How is the wishlist link outputted? Trough wp_nav_menu? I would add it to the link on creation, so you don't have to use wp_redirect.</p>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80171/"
] |
I am trying to add a function to my child theme to append the currently logged user as a parameter. For example, when the user test1 logs in and clicks on the following page:
```
http://www.example.com/my-wishlist
```
I want her to be redirected automatically to
```
http://www.example.com/my-wishlist/?user=test1
```
So far I did the following but it ends in a loop:
```
$current_user = wp_get_current_user();
if ( is_user_logged_in() ) {
wp_redirect( 'http://www.example.com/my-wishlist/?user='.$current_user->user_login );
exit;
}
```
I would appreciate some help. Thank you
|
Use [add\_query\_arg](https://developer.wordpress.org/reference/functions/add_query_arg/) to make sure the url is created the right way. How is the wishlist link outputted? Trough wp\_nav\_menu? I would add it to the link on creation, so you don't have to use wp\_redirect.
|
202,323 |
<p>I am on Archive Page of a custom post type <code>gallery</code>.</p>
<p>I have introduced custom permalink variable - <code>author_id</code>.</p>
<p>Lets say i get the permalink variable in <code>$perm_author_id</code>. I want to compare <code>$perm_author_id</code> and <code>get_the_author_meta(ID)</code> and then display the posts if they are equal.</p>
<p>How can I limit posts displayed on the archive page on to those posts posted by author whose <code>author_id</code> is present in permalink?</p>
|
[
{
"answer_id": 202333,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>What you want to do is commonly known as modifying the main query. There are a lot of faulty advice out there on topic, guiding to make the modification in template — <strong>don't</strong>.</p>\n\n<p>The most common approach has following steps:</p>\n\n<ol>\n<li>Use appropriate hook, typically this would be <code>pre_get_posts</code>.</li>\n<li>Check that you work with correct instance of query object, using its methods. In your case to verify that it's <em>main</em> query and required archive.</li>\n<li>Modify query by adding your custom author argument.</li>\n</ol>\n\n<p>It's a little vague how you have implemented the permalink logic, but some searching and reading up on <code>pre_get_posts</code> should get you started.</p>\n"
},
{
"answer_id": 202337,
"author": "mirado",
"author_id": 79879,
"author_profile": "https://wordpress.stackexchange.com/users/79879",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function comment_author_id($query) {\n $author_id = get_query_var( 'hotel_name' );\n if ($author_id) {\n $query->set('author', $author_id);\n }\n\n}\nadd_action( 'pre_get_posts', 'comment_author_id' );\n</code></pre>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202323",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
I am on Archive Page of a custom post type `gallery`.
I have introduced custom permalink variable - `author_id`.
Lets say i get the permalink variable in `$perm_author_id`. I want to compare `$perm_author_id` and `get_the_author_meta(ID)` and then display the posts if they are equal.
How can I limit posts displayed on the archive page on to those posts posted by author whose `author_id` is present in permalink?
|
```
function comment_author_id($query) {
$author_id = get_query_var( 'hotel_name' );
if ($author_id) {
$query->set('author', $author_id);
}
}
add_action( 'pre_get_posts', 'comment_author_id' );
```
|
202,325 |
<p>I want to know how I can change the structure of the permalink to my desired one before saving or publishing my post in Wordpress?<br/>
For instance, when I add the title like <code>the wordpress blog</code> in my post I get the permalink structure similar to the below:<br/></p>
<pre><code>http://localhost/2015/09/10/the-wordpress-blog/
</code></pre>
<p>I want to change it to something like below before saving or publishing it:<br/></p>
<pre><code>http://localhost/2015/09/10/the-wordpress-blog-is-mine/
</code></pre>
<p>But I don't know hook what into what to achieve my goal.</p>
|
[
{
"answer_id": 202330,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>Underneath the Title field is the slug field. Normally WordPress will automatically create a slug base on what you are typing in the Title field. All you need to do is type in what you want that to be and then publish.</p>\n"
},
{
"answer_id": 202334,
"author": "FreeMind",
"author_id": 75180,
"author_profile": "https://wordpress.stackexchange.com/users/75180",
"pm_score": 1,
"selected": false,
"text": "<p>Finally, I found my answer on my own.</p>\n\n<pre><code>//add our action\nadd_action( 'save_post', 'my_save_post', 11, 2 );\n\nfunction my_save_post($post_id, $post){\n\n //if it is just a revision don't worry about it\n if (wp_is_post_revision($post_id))\n return false;\n\n //if the post is an auto-draft we don't want to do anything either\n if($post->post_status != 'auto-draft' ){\n\n // unhook this function so it doesn't loop infinitely\n remove_action('save_post', 'my_save_post' );\n\n //this is where it happens -- update the post and change the post_name/slug to the post_title\n wp_update_post(array('ID' => $post_id, 'post_name' => str_replace(' ', '-', $_POST['post_title'])));\n\n //re-hook this function\n add_action('save_post', 'my_save_post' );\n }\n}\n</code></pre>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202325",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75180/"
] |
I want to know how I can change the structure of the permalink to my desired one before saving or publishing my post in Wordpress?
For instance, when I add the title like `the wordpress blog` in my post I get the permalink structure similar to the below:
```
http://localhost/2015/09/10/the-wordpress-blog/
```
I want to change it to something like below before saving or publishing it:
```
http://localhost/2015/09/10/the-wordpress-blog-is-mine/
```
But I don't know hook what into what to achieve my goal.
|
Finally, I found my answer on my own.
```
//add our action
add_action( 'save_post', 'my_save_post', 11, 2 );
function my_save_post($post_id, $post){
//if it is just a revision don't worry about it
if (wp_is_post_revision($post_id))
return false;
//if the post is an auto-draft we don't want to do anything either
if($post->post_status != 'auto-draft' ){
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'my_save_post' );
//this is where it happens -- update the post and change the post_name/slug to the post_title
wp_update_post(array('ID' => $post_id, 'post_name' => str_replace(' ', '-', $_POST['post_title'])));
//re-hook this function
add_action('save_post', 'my_save_post' );
}
}
```
|
202,342 |
<p>I am working on setting up the customizer for my theme. I have all of the sections and controls I need, but now I am trying to make some of them only show on certain pages.</p>
<p>My first stop is the sections that relate only to the home page. I read <a href="https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_section" rel="nofollow" title="here">here</a> that I can add an argument called "active_callback" tp the arguments object and pass it a check function such as <code>is_front_page</code> or <code>is_home</code>.</p>
<p>Seemed easy, until I tried it and it didn't work. I've tried everything I could think of (this is my first foray into WordPress), so now I am coming to you all hoping you can answer my question</p>
<p>I am customizing the customizer in <code>functions.php</code> like such:</p>
<pre><code>add_action( 'customize_register', 'ablogs_theme_customizer' );
function ablogs_theme_customizer($wp_customize) {
$wp_customize->add_section( 'home-page-slider-settings', array(
'title' => "Slider Settings",
'priority' => 0,
'active_callback' => 'is_front_page'
));
}
</code></pre>
<p>If I take off the active callback argument, it shows up just fine, but on every page while customizing. I really need this to only show up on the home page. I am not using a static front page. I am running a custom <code>front-page.php</code> file that acts as the front page, so I am guessing that should count as both <code>front-page</code> and <code>home</code> when checking for those values, both of which I have tried.</p>
<p>Can anybody help me out here</p>
|
[
{
"answer_id": 202355,
"author": "StephenRios",
"author_id": 80200,
"author_profile": "https://wordpress.stackexchange.com/users/80200",
"pm_score": 3,
"selected": true,
"text": "<p>The problem was I had multiple loops that each had different queries on the front page. After making sure to reset them each time, this problem resolved itself.</p>\n\n<p>For instance, my new query and loop looks like this:</p>\n\n<pre><code>query_posts( array(\n 'category_name'=>\"Cloud, Customer Engagement, Developers, Executive Thought Leadership, Networking, Services, Solutions, Team Engagement\",\n 'showposts'=>8,\n 'order'=>DESC\n));\n\n// Start the loop\nif ( have_posts() ) : while ( have_posts() ) : the_post();\n\n echo '<div class=\"post-card-wrap\">';\n\n // Get the card\n get_category_post_card($post);\n\n echo '</div>';\n\n// End the loop\nendwhile; endif;\n\n// Reset the query\nwp_reset_query();\n</code></pre>\n"
},
{
"answer_id": 296484,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>Replace your code with this code: <a href=\"http://ottopress.com/2015/whats-new-with-the-customizer/\" rel=\"nofollow noreferrer\">FOR MORE INFO</a></p>\n\n<pre><code>add_action( 'customize_register', 'ablogs_theme_customizer' );\nfunction ablogs_theme_customizer($wp_customize) {\n $wp_customize->add_section( 'home-page-slider-settings', array( \n 'title' => \"Slider Settings\",\n 'priority' => 0,\n 'active_callback' => 'callback_single'\n ));\n} \n\nfunction callback_single() { return is_home(); }\n</code></pre>\n\n<p>NOTE: Just try it. code is not tested. hope it's working.</p>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202342",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80200/"
] |
I am working on setting up the customizer for my theme. I have all of the sections and controls I need, but now I am trying to make some of them only show on certain pages.
My first stop is the sections that relate only to the home page. I read [here](https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_section "here") that I can add an argument called "active\_callback" tp the arguments object and pass it a check function such as `is_front_page` or `is_home`.
Seemed easy, until I tried it and it didn't work. I've tried everything I could think of (this is my first foray into WordPress), so now I am coming to you all hoping you can answer my question
I am customizing the customizer in `functions.php` like such:
```
add_action( 'customize_register', 'ablogs_theme_customizer' );
function ablogs_theme_customizer($wp_customize) {
$wp_customize->add_section( 'home-page-slider-settings', array(
'title' => "Slider Settings",
'priority' => 0,
'active_callback' => 'is_front_page'
));
}
```
If I take off the active callback argument, it shows up just fine, but on every page while customizing. I really need this to only show up on the home page. I am not using a static front page. I am running a custom `front-page.php` file that acts as the front page, so I am guessing that should count as both `front-page` and `home` when checking for those values, both of which I have tried.
Can anybody help me out here
|
The problem was I had multiple loops that each had different queries on the front page. After making sure to reset them each time, this problem resolved itself.
For instance, my new query and loop looks like this:
```
query_posts( array(
'category_name'=>"Cloud, Customer Engagement, Developers, Executive Thought Leadership, Networking, Services, Solutions, Team Engagement",
'showposts'=>8,
'order'=>DESC
));
// Start the loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo '<div class="post-card-wrap">';
// Get the card
get_category_post_card($post);
echo '</div>';
// End the loop
endwhile; endif;
// Reset the query
wp_reset_query();
```
|
202,362 |
<p>I can already unset (remove specifics from normal posts) in the json returned from the WordPress API. I actually use the following below from this example: <a href="https://css-tricks.com/using-the-wp-api-to-fetch-posts/" rel="nofollow">https://css-tricks.com/using-the-wp-api-to-fetch-posts/</a></p>
<p>What I am having trouble with and can't figure out, is how to change this so it unsets data from a <strong>Custom Post Type</strong></p>
<p>Thoughts?</p>
<pre><code>function qod_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
unset( $data['featured_image'] );
//etc etc
return $data;
}
add_filter( 'json_prepare_post', 'qod_remove_extra_data', 12, 3 );
</code></pre>
<p>new example with custom post type **</p>
<pre><code>function projectPost_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
return $data;
}
add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );
</code></pre>
|
[
{
"answer_id": 206790,
"author": "brianlmerritt",
"author_id": 78419,
"author_profile": "https://wordpress.stackexchange.com/users/78419",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at the wp-api code for pages (which are custom post types).</p>\n\n<p>You can modify the code, changing pages to whatever your post type is called (just be careful about doing a search and replace for all \"pages\" as some of them are wordpress function calls or filters)</p>\n\n<pre><code><?php\n/**\n * Page post type handlers\n *\n * @package WordPress\n * @subpackage JSON API\n */\n\n/**\n * Page post type handlers\n *\n * This class serves as a small addition on top of the basic post handlers to\n * add small functionality on top of the existing API.\n *\n * In addition, this class serves as a sample implementation of building on top\n * of the existing APIs for custom post types.\n *\n * @package WordPress\n * @subpackage JSON API\n */\nclass WP_JSON_Pages extends WP_JSON_CustomPostType {\n /**\n * Base route\n *\n * @var string\n */\n protected $base = '/pages';\n\n /**\n * Post type\n *\n * @var string\n */\n protected $type = 'page';\n\n /**\n * Register the page-related routes\n *\n * @param array $routes Existing routes\n * @return array Modified routes\n */\n public function register_routes( $routes ) {\n $routes = parent::register_routes( $routes );\n $routes = parent::register_revision_routes( $routes );\n $routes = parent::register_comment_routes( $routes );\n\n // Add post-by-path routes\n $routes[ $this->base . '/(?P<path>.+)'] = array(\n array( array( $this, 'get_post_by_path' ), WP_JSON_Server::READABLE ),\n array( array( $this, 'edit_post_by_path' ), WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),\n array( array( $this, 'delete_post_by_path' ), WP_JSON_Server::DELETABLE ),\n );\n\n return $routes;\n }\n\n /**\n * Retrieve a page by path name\n *\n * @param string $path\n * @param string $context\n *\n * @return array|WP_Error\n */\n public function get_post_by_path( $path, $context = 'view' ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->get_post( $post['ID'], $context );\n }\n\n /**\n * Edit a page by path name\n *\n * @param $path\n * @param $data\n * @param array $_headers\n *\n * @return true|WP_Error\n */\n public function edit_post_by_path( $path, $data, $_headers = array() ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->edit_post( $post['ID'], $data, $_headers );\n }\n\n /**\n * Delete a page by path name\n *\n * @param $path\n * @param bool $force\n *\n * @return true|WP_Error\n */\n public function delete_post_by_path( $path, $force = false ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->delete_post( $post['ID'], $force );\n }\n\n /**\n * Prepare post data\n *\n * @param array $post The unprepared post data\n * @param string $context The context for the prepared post. (view|view-revision|edit|embed|single-parent)\n * @return array The prepared post data\n */\n protected function prepare_post( $post, $context = 'view' ) {\n $_post = parent::prepare_post( $post, $context );\n\n // Override entity meta keys with the correct links\n $_post['meta']['links']['self'] = json_url( $this->base . '/' . get_page_uri( $post['ID'] ) );\n\n if ( ! empty( $post['post_parent'] ) ) {\n $_post['meta']['links']['up'] = json_url( $this->base . '/' . get_page_uri( (int) $post['post_parent'] ) );\n }\n\n return apply_filters( 'json_prepare_page', $_post, $post, $context );\n }\n}\n</code></pre>\n\n<p>Put your custom code in edit or filter etc, and away you go!</p>\n\n<p>ps - don't forget to turn it into a proper plugin! You can add as a new plugin and manage it better that way using:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: My JSON App API\n * Description: My Route and Endpoint handler for the JSON API\n * Dependency: This plugin requires JSON BasicKey Authentication Plugin!!!! \n * Author: Blah Blah Blah, plus much original code from the WordPress API Team\n * Author URI: https://www.example.com\n * Version: 1.2\n * Plugin URI: https://www.example.com\n */\n\nif ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly\nif (!defined(\"MY_JSON_API_VERSION\")) {\n define (\"MY_JSON_API_VERSION\", \"1.2\") ;\n}\n\nfunction my_json_api_init() {\n global $my_json_api_mobile_users;\n $my_json_api_mobile_users = new my_JSON_API_MobileUsers();\n add_filter( 'json_endpoints', array( $my_json_api_mobile_users, 'register_routes' ) );\n}\nadd_action( 'wp_json_server_before_serve', 'my_json_api_init' );\n</code></pre>\n"
},
{
"answer_id": 213790,
"author": "Cristopher Gonzalez Vega",
"author_id": 86314,
"author_profile": "https://wordpress.stackexchange.com/users/86314",
"pm_score": 4,
"selected": true,
"text": "<p>If possible, only the examples shown in internet is:</p>\n<pre><code>function qod_remove_extra_data($data, $post, $context) {\n // We only want to modify the 'view' context, for reading posts \n if ($context !== 'view' || is_wp_error($data)) {\n return $data; \n } \n // Here, we unset any data we do not want to see on the front end: \n unset($data['author']); \n unset($data['status']); \n // Continue unsetting whatever other fields you want return $ data;\n}\nadd_filter('json_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>and right is:</p>\n<pre><code>function qod_remove_extra_data($data, $post, $context) {\n // We only want to modify the 'view' context, for reading posts \n if ($context !== 'view' || is_wp_error($data)) {\n unset ( $data->data['excerpt']); //Example\n unset ($data->data['content']); //Example\n unset ($data->data['name field to remove']); \n //or \n unset ($data->data['name field to remove']['name subfield if you only want to delete the sub-field of field']); \n return $data; \n }\n}\nadd_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>IMPORTANT:\nIs:</p>\n<pre><code>add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>Not:</p>\n<pre><code>add_filter('json_prepare_post', 'qod remove extra_data', 12, 3); //WRONG (No underscores)\n</code></pre>\n<p>If is Custom Post Type:</p>\n<pre><code>add_filter('rest_prepare_{$post_type}', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>EXAMPLE: Name post type = product;</p>\n<pre><code> add_filter('rest_prepare_product', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>With this code can remove the fields that you want the JSON. By using rest_prepare}_{$ post_type decide that you eliminated every post_type fields, thus only affected the post_type you want and not all.</p>\n"
}
] |
2015/09/10
|
[
"https://wordpress.stackexchange.com/questions/202362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57278/"
] |
I can already unset (remove specifics from normal posts) in the json returned from the WordPress API. I actually use the following below from this example: <https://css-tricks.com/using-the-wp-api-to-fetch-posts/>
What I am having trouble with and can't figure out, is how to change this so it unsets data from a **Custom Post Type**
Thoughts?
```
function qod_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
unset( $data['featured_image'] );
//etc etc
return $data;
}
add_filter( 'json_prepare_post', 'qod_remove_extra_data', 12, 3 );
```
new example with custom post type \*\*
```
function projectPost_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
return $data;
}
add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );
```
|
If possible, only the examples shown in internet is:
```
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
return $data;
}
// Here, we unset any data we do not want to see on the front end:
unset($data['author']);
unset($data['status']);
// Continue unsetting whatever other fields you want return $ data;
}
add_filter('json_prepare_post', 'qod_remove_extra_data', 12, 3);
```
and right is:
```
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
unset ( $data->data['excerpt']); //Example
unset ($data->data['content']); //Example
unset ($data->data['name field to remove']);
//or
unset ($data->data['name field to remove']['name subfield if you only want to delete the sub-field of field']);
return $data;
}
}
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
```
IMPORTANT:
Is:
```
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
```
Not:
```
add_filter('json_prepare_post', 'qod remove extra_data', 12, 3); //WRONG (No underscores)
```
If is Custom Post Type:
```
add_filter('rest_prepare_{$post_type}', 'qod_remove_extra_data', 12, 3);
```
EXAMPLE: Name post type = product;
```
add_filter('rest_prepare_product', 'qod_remove_extra_data', 12, 3);
```
With this code can remove the fields that you want the JSON. By using rest\_prepare}\_{$ post\_type decide that you eliminated every post\_type fields, thus only affected the post\_type you want and not all.
|
202,372 |
<p>i want to add a page with html data to show form and get input from user,store it to database and after successful query show next page with massage that the data is inserted successfully.</p>
|
[
{
"answer_id": 206790,
"author": "brianlmerritt",
"author_id": 78419,
"author_profile": "https://wordpress.stackexchange.com/users/78419",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at the wp-api code for pages (which are custom post types).</p>\n\n<p>You can modify the code, changing pages to whatever your post type is called (just be careful about doing a search and replace for all \"pages\" as some of them are wordpress function calls or filters)</p>\n\n<pre><code><?php\n/**\n * Page post type handlers\n *\n * @package WordPress\n * @subpackage JSON API\n */\n\n/**\n * Page post type handlers\n *\n * This class serves as a small addition on top of the basic post handlers to\n * add small functionality on top of the existing API.\n *\n * In addition, this class serves as a sample implementation of building on top\n * of the existing APIs for custom post types.\n *\n * @package WordPress\n * @subpackage JSON API\n */\nclass WP_JSON_Pages extends WP_JSON_CustomPostType {\n /**\n * Base route\n *\n * @var string\n */\n protected $base = '/pages';\n\n /**\n * Post type\n *\n * @var string\n */\n protected $type = 'page';\n\n /**\n * Register the page-related routes\n *\n * @param array $routes Existing routes\n * @return array Modified routes\n */\n public function register_routes( $routes ) {\n $routes = parent::register_routes( $routes );\n $routes = parent::register_revision_routes( $routes );\n $routes = parent::register_comment_routes( $routes );\n\n // Add post-by-path routes\n $routes[ $this->base . '/(?P<path>.+)'] = array(\n array( array( $this, 'get_post_by_path' ), WP_JSON_Server::READABLE ),\n array( array( $this, 'edit_post_by_path' ), WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),\n array( array( $this, 'delete_post_by_path' ), WP_JSON_Server::DELETABLE ),\n );\n\n return $routes;\n }\n\n /**\n * Retrieve a page by path name\n *\n * @param string $path\n * @param string $context\n *\n * @return array|WP_Error\n */\n public function get_post_by_path( $path, $context = 'view' ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->get_post( $post['ID'], $context );\n }\n\n /**\n * Edit a page by path name\n *\n * @param $path\n * @param $data\n * @param array $_headers\n *\n * @return true|WP_Error\n */\n public function edit_post_by_path( $path, $data, $_headers = array() ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->edit_post( $post['ID'], $data, $_headers );\n }\n\n /**\n * Delete a page by path name\n *\n * @param $path\n * @param bool $force\n *\n * @return true|WP_Error\n */\n public function delete_post_by_path( $path, $force = false ) {\n $post = get_page_by_path( $path, ARRAY_A );\n\n if ( empty( $post ) ) {\n return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );\n }\n\n return $this->delete_post( $post['ID'], $force );\n }\n\n /**\n * Prepare post data\n *\n * @param array $post The unprepared post data\n * @param string $context The context for the prepared post. (view|view-revision|edit|embed|single-parent)\n * @return array The prepared post data\n */\n protected function prepare_post( $post, $context = 'view' ) {\n $_post = parent::prepare_post( $post, $context );\n\n // Override entity meta keys with the correct links\n $_post['meta']['links']['self'] = json_url( $this->base . '/' . get_page_uri( $post['ID'] ) );\n\n if ( ! empty( $post['post_parent'] ) ) {\n $_post['meta']['links']['up'] = json_url( $this->base . '/' . get_page_uri( (int) $post['post_parent'] ) );\n }\n\n return apply_filters( 'json_prepare_page', $_post, $post, $context );\n }\n}\n</code></pre>\n\n<p>Put your custom code in edit or filter etc, and away you go!</p>\n\n<p>ps - don't forget to turn it into a proper plugin! You can add as a new plugin and manage it better that way using:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: My JSON App API\n * Description: My Route and Endpoint handler for the JSON API\n * Dependency: This plugin requires JSON BasicKey Authentication Plugin!!!! \n * Author: Blah Blah Blah, plus much original code from the WordPress API Team\n * Author URI: https://www.example.com\n * Version: 1.2\n * Plugin URI: https://www.example.com\n */\n\nif ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly\nif (!defined(\"MY_JSON_API_VERSION\")) {\n define (\"MY_JSON_API_VERSION\", \"1.2\") ;\n}\n\nfunction my_json_api_init() {\n global $my_json_api_mobile_users;\n $my_json_api_mobile_users = new my_JSON_API_MobileUsers();\n add_filter( 'json_endpoints', array( $my_json_api_mobile_users, 'register_routes' ) );\n}\nadd_action( 'wp_json_server_before_serve', 'my_json_api_init' );\n</code></pre>\n"
},
{
"answer_id": 213790,
"author": "Cristopher Gonzalez Vega",
"author_id": 86314,
"author_profile": "https://wordpress.stackexchange.com/users/86314",
"pm_score": 4,
"selected": true,
"text": "<p>If possible, only the examples shown in internet is:</p>\n<pre><code>function qod_remove_extra_data($data, $post, $context) {\n // We only want to modify the 'view' context, for reading posts \n if ($context !== 'view' || is_wp_error($data)) {\n return $data; \n } \n // Here, we unset any data we do not want to see on the front end: \n unset($data['author']); \n unset($data['status']); \n // Continue unsetting whatever other fields you want return $ data;\n}\nadd_filter('json_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>and right is:</p>\n<pre><code>function qod_remove_extra_data($data, $post, $context) {\n // We only want to modify the 'view' context, for reading posts \n if ($context !== 'view' || is_wp_error($data)) {\n unset ( $data->data['excerpt']); //Example\n unset ($data->data['content']); //Example\n unset ($data->data['name field to remove']); \n //or \n unset ($data->data['name field to remove']['name subfield if you only want to delete the sub-field of field']); \n return $data; \n }\n}\nadd_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>IMPORTANT:\nIs:</p>\n<pre><code>add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>Not:</p>\n<pre><code>add_filter('json_prepare_post', 'qod remove extra_data', 12, 3); //WRONG (No underscores)\n</code></pre>\n<p>If is Custom Post Type:</p>\n<pre><code>add_filter('rest_prepare_{$post_type}', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>EXAMPLE: Name post type = product;</p>\n<pre><code> add_filter('rest_prepare_product', 'qod_remove_extra_data', 12, 3);\n</code></pre>\n<p>With this code can remove the fields that you want the JSON. By using rest_prepare}_{$ post_type decide that you eliminated every post_type fields, thus only affected the post_type you want and not all.</p>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202372",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80223/"
] |
i want to add a page with html data to show form and get input from user,store it to database and after successful query show next page with massage that the data is inserted successfully.
|
If possible, only the examples shown in internet is:
```
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
return $data;
}
// Here, we unset any data we do not want to see on the front end:
unset($data['author']);
unset($data['status']);
// Continue unsetting whatever other fields you want return $ data;
}
add_filter('json_prepare_post', 'qod_remove_extra_data', 12, 3);
```
and right is:
```
function qod_remove_extra_data($data, $post, $context) {
// We only want to modify the 'view' context, for reading posts
if ($context !== 'view' || is_wp_error($data)) {
unset ( $data->data['excerpt']); //Example
unset ($data->data['content']); //Example
unset ($data->data['name field to remove']);
//or
unset ($data->data['name field to remove']['name subfield if you only want to delete the sub-field of field']);
return $data;
}
}
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
```
IMPORTANT:
Is:
```
add_filter('rest_prepare_post', 'qod_remove_extra_data', 12, 3);
```
Not:
```
add_filter('json_prepare_post', 'qod remove extra_data', 12, 3); //WRONG (No underscores)
```
If is Custom Post Type:
```
add_filter('rest_prepare_{$post_type}', 'qod_remove_extra_data', 12, 3);
```
EXAMPLE: Name post type = product;
```
add_filter('rest_prepare_product', 'qod_remove_extra_data', 12, 3);
```
With this code can remove the fields that you want the JSON. By using rest\_prepare}\_{$ post\_type decide that you eliminated every post\_type fields, thus only affected the post\_type you want and not all.
|
202,408 |
<p>I've a theme which loads 'Open Sans' from Google Fonts. Our site is using SSL & we're using a <code>$protocol://</code> to render the font URL</p>
<p>However, I noticed that, some plugin/(s) probably adding 3 different fonts from Google Fonts, & they're being loaded using <code>http://</code> & that throws error such as:</p>
<p><code>Blocked loading mixed active content "http://fonts.googleapis.com/css?family=Lato:300,400,700"</code> </p>
<p><strong>Question:</strong> How do we disable fonts loaded from plugins, on the frontend, since they're not used in visual sense of the website</p>
<p>Thanks in advance :)</p>
|
[
{
"answer_id": 202415,
"author": "phoenixlaef",
"author_id": 37261,
"author_profile": "https://wordpress.stackexchange.com/users/37261",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to make a comment to mention this but I don't have enough rep yet to do so. I had a problem similar to this and I used a simple plugin as a basis to solve the issue. You might be able to do the same.</p>\n\n<p>Checkout <a href=\"https://github.com/dimadin/disable-google-fonts/blob/master/disable-google-fonts.php\" rel=\"nofollow\">disable-google-fonts</a> on GitHub. It disables various google fonts found in Wordpress themes. You could modify this or use snippets of the code to do what you need.</p>\n"
},
{
"answer_id": 202419,
"author": "totels",
"author_id": 23446,
"author_profile": "https://wordpress.stackexchange.com/users/23446",
"pm_score": 3,
"selected": true,
"text": "<p>If the fonts are loaded from a plugin, a hook will have to be used to insert them, you can disable the hook, but you'll need to know where it's coming from. Mostly because you'll need the handle of the script.</p>\n\n<p>There are quite a few different ways it could be done so I'll try to give an example of one way it may be done, but there's a good chance you'll need to do some hunting yourself.</p>\n\n<p>The plugin could be (ideally is) loading it directly with <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\"><code>wp_enqueue_style()</code></a>, lucky for us there's a function for reversing that action <a href=\"http://codex.wordpress.org/Function_Reference/wp_dequeue_style\" rel=\"nofollow\"><code>wp_dequeue_style()</code></a>, you just need to make sure you hook in at the right time and you can remove it. In most cases this is done in the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> hook. It's possible they have set a high priority to make it load late, but that's not usually necessary, you may need to find exactly how they do it to be sure.</p>\n\n<p>somewhere in the plugin may be a few lines of code something like:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'plugin_setup_styles' );\n\nfunction plugin_setup_styles() {\n // it may not be quite this simple, depending on what the plugin is doing\n wp_register_style( 'plugin-google-font-lato', 'http://fonts.googleapis.com/css?family=Lato:300,400,700' );\n wp_enqueue_style( 'plugin-google-font-lato' );\n}\n</code></pre>\n\n<p>possible solution, should work from functions.php:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function() {\n wp_dequeue_style( 'plugin-google-font-lato' );\n}, 99 );\n</code></pre>\n\n<p>Basically, you're going to need to know the handle of the script as it is registered, <code>grep</code> is great for this <code>$ grep -R wp_enqueue_style wp-content/plugins/</code> as a start. But you may get better results searching for Lato <code>$ grep -Rn Lato wp-content/plugins/</code></p>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15946/"
] |
I've a theme which loads 'Open Sans' from Google Fonts. Our site is using SSL & we're using a `$protocol://` to render the font URL
However, I noticed that, some plugin/(s) probably adding 3 different fonts from Google Fonts, & they're being loaded using `http://` & that throws error such as:
`Blocked loading mixed active content "http://fonts.googleapis.com/css?family=Lato:300,400,700"`
**Question:** How do we disable fonts loaded from plugins, on the frontend, since they're not used in visual sense of the website
Thanks in advance :)
|
If the fonts are loaded from a plugin, a hook will have to be used to insert them, you can disable the hook, but you'll need to know where it's coming from. Mostly because you'll need the handle of the script.
There are quite a few different ways it could be done so I'll try to give an example of one way it may be done, but there's a good chance you'll need to do some hunting yourself.
The plugin could be (ideally is) loading it directly with [`wp_enqueue_style()`](http://codex.wordpress.org/Function_Reference/wp_enqueue_style), lucky for us there's a function for reversing that action [`wp_dequeue_style()`](http://codex.wordpress.org/Function_Reference/wp_dequeue_style), you just need to make sure you hook in at the right time and you can remove it. In most cases this is done in the [`wp_enqueue_scripts`](http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) hook. It's possible they have set a high priority to make it load late, but that's not usually necessary, you may need to find exactly how they do it to be sure.
somewhere in the plugin may be a few lines of code something like:
```
add_action( 'wp_enqueue_scripts', 'plugin_setup_styles' );
function plugin_setup_styles() {
// it may not be quite this simple, depending on what the plugin is doing
wp_register_style( 'plugin-google-font-lato', 'http://fonts.googleapis.com/css?family=Lato:300,400,700' );
wp_enqueue_style( 'plugin-google-font-lato' );
}
```
possible solution, should work from functions.php:
```
add_action( 'wp_enqueue_scripts', function() {
wp_dequeue_style( 'plugin-google-font-lato' );
}, 99 );
```
Basically, you're going to need to know the handle of the script as it is registered, `grep` is great for this `$ grep -R wp_enqueue_style wp-content/plugins/` as a start. But you may get better results searching for Lato `$ grep -Rn Lato wp-content/plugins/`
|
202,418 |
<p>How can i limit comments displayed on the page - <code>reviews</code> by <code>author_id</code>. </p>
<p>Lets say that the <code>author_id</code> to limit to is in variable <code>$author_id_to_limit</code>.</p>
<p>Please tell me how to hook the function to do so.</p>
<p>I would even like to know how to edit the no of post with this cuurent query.</p>
|
[
{
"answer_id": 202420,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": false,
"text": "<p>Hi Just need to make your function to get comments and then use your function output at required places.</p>\n\n<pre><code><?php get_comments( $args ); ?>\n\n<?php $args = array(\n'user_id' => $author_id_to_limit, ); \n\nget_comments( $args ); ?>\n</code></pre>\n\n<p>Set Number to your variable like I did in above code. Rest of args please put accordingly.</p>\n\n<p>For details follow this link below:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_comments\" rel=\"nofollow\">get_comments</a></p>\n"
},
{
"answer_id": 202421,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>The <code>pre_get_comments</code> hook</h2>\n\n<p>Note that the single post's comments are fetched with <code>get_comments()</code>, within the <code>comment_template()</code> function.</p>\n\n<p>The <code>get_comments()</code> function is just a <code>WP_Comment_Query</code> object wrapper, so we can restrict the comment query with the <code>pre_get_comments</code> hook.</p>\n\n<h2>Example #1</h2>\n\n<p>Here's a simple <code>user_id</code> restriction example:</p>\n\n<pre><code>! is_admin() && add_action( 'pre_get_comments', function( \\WP_Comment_Query $q )\n{\n if( $uid = get_query_var( 'author_id_to_limit' ) )\n $q->query_vars['user_id'] = (int) $uid; \n});\n</code></pre>\n\n<p>where you might add further constraints, so you don't modify other comment lists.</p>\n\n<h2>Example #2</h2>\n\n<p>We could restrict it more with:</p>\n\n<pre><code>// Let's begin where the main loop starts:\nadd_action( 'loop_start', function( \\WP_Query $q )\n{\n // Target the main loop\n if( ! in_the_loop() )\n return;\n\n // Modify the get_comments() call\n add_action( 'pre_get_comments', function( \\WP_Comment_Query $q )\n {\n if( \n $uid = get_query_var( 'author_id_to_limit' ) // Get the user input\n && ! did_action( 'wpse_mods' ) // Run this only once\n\n ) {\n // Set the comment user id\n $q->query_vars['user_id'] = (int) $uid; \n\n // Activate the temporary action\n do_action( 'wpse_mods' );\n }\n });\n});\n</code></pre>\n\n<p>i.e. we want to target the first <code>get_comments()</code> call after the main loop starts.</p>\n\n<p>You might use other hooks, some themes have specific hooks that might be easier to target.</p>\n\n<h2>Modify the comments count accordingly</h2>\n\n<p>If we want to modify the displayed comments number, then we could use the <code>get_comments_number</code> filter.</p>\n\n<p>The <code>get_comments_number()</code> function uses the <code>comment_count</code> property of the $post object, that originates from the <code>wp_posts</code> table. So that will not help us here.</p>\n\n<p>We can instead re-use the comments query, to update the comment number, exactly when our temporary <code>wpse_mods</code> action as fired only once (you might have to adjust that to your needs)</p>\n\n<pre><code>! is_admin() && add_action( 'the_comments', function( $comments, \\WP_Comment_Query $q )\n{\n $request = $q->request;\n\n add_filter( 'get_comments_number', function( $number ) use ( $request ) \n {\n // Override the comments number after our previous modifications\n if( 1 === did_action( 'wpse_mods' ) )\n { \n global $wpdb; \n // Modify the comments query to our needs:\n $number = $wpdb->get_var( \n str_replace( \n 'SELECT * ', \n 'SELECT COUNT(*) ', \n $request \n )\n );\n }\n return $number;\n } ); \n return $comments;\n}, 10, 2 );\n</code></pre>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202418",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
How can i limit comments displayed on the page - `reviews` by `author_id`.
Lets say that the `author_id` to limit to is in variable `$author_id_to_limit`.
Please tell me how to hook the function to do so.
I would even like to know how to edit the no of post with this cuurent query.
|
The `pre_get_comments` hook
---------------------------
Note that the single post's comments are fetched with `get_comments()`, within the `comment_template()` function.
The `get_comments()` function is just a `WP_Comment_Query` object wrapper, so we can restrict the comment query with the `pre_get_comments` hook.
Example #1
----------
Here's a simple `user_id` restriction example:
```
! is_admin() && add_action( 'pre_get_comments', function( \WP_Comment_Query $q )
{
if( $uid = get_query_var( 'author_id_to_limit' ) )
$q->query_vars['user_id'] = (int) $uid;
});
```
where you might add further constraints, so you don't modify other comment lists.
Example #2
----------
We could restrict it more with:
```
// Let's begin where the main loop starts:
add_action( 'loop_start', function( \WP_Query $q )
{
// Target the main loop
if( ! in_the_loop() )
return;
// Modify the get_comments() call
add_action( 'pre_get_comments', function( \WP_Comment_Query $q )
{
if(
$uid = get_query_var( 'author_id_to_limit' ) // Get the user input
&& ! did_action( 'wpse_mods' ) // Run this only once
) {
// Set the comment user id
$q->query_vars['user_id'] = (int) $uid;
// Activate the temporary action
do_action( 'wpse_mods' );
}
});
});
```
i.e. we want to target the first `get_comments()` call after the main loop starts.
You might use other hooks, some themes have specific hooks that might be easier to target.
Modify the comments count accordingly
-------------------------------------
If we want to modify the displayed comments number, then we could use the `get_comments_number` filter.
The `get_comments_number()` function uses the `comment_count` property of the $post object, that originates from the `wp_posts` table. So that will not help us here.
We can instead re-use the comments query, to update the comment number, exactly when our temporary `wpse_mods` action as fired only once (you might have to adjust that to your needs)
```
! is_admin() && add_action( 'the_comments', function( $comments, \WP_Comment_Query $q )
{
$request = $q->request;
add_filter( 'get_comments_number', function( $number ) use ( $request )
{
// Override the comments number after our previous modifications
if( 1 === did_action( 'wpse_mods' ) )
{
global $wpdb;
// Modify the comments query to our needs:
$number = $wpdb->get_var(
str_replace(
'SELECT * ',
'SELECT COUNT(*) ',
$request
)
);
}
return $number;
} );
return $comments;
}, 10, 2 );
```
|
202,432 |
<p>I know I'm doing something that's been done 1000's of times before in WordPress, but struggling to get the terms to find it on the Interwebs.</p>
<p>I've got a custom category template page and have a while loop that shows the first 5 results (of which there are more than 5).</p>
<p>How do I output something within my while that shows the relative position in the results and the total number:</p>
<p>I know how to get the post count:</p>
<pre><code><?php
$catcount = new WP_Query( 'cat=4&posts_per_page=-1' );
?>
</code></pre>
<p>But not sure how to setup the pagination and the relative results, meaning</p>
<p>Results 1-10 of <code><?php echo $total->found_posts; ?></code></p>
<p>How do I get the results values 1 of 2 and then create pagination for subsequent pages?</p>
|
[
{
"answer_id": 202438,
"author": "webmaven",
"author_id": 80260,
"author_profile": "https://wordpress.stackexchange.com/users/80260",
"pm_score": -1,
"selected": false,
"text": "<p>Ok so, This following is how you can have custom wp query with pagination, I also suggest you install this plugin: <a href=\"https://wordpress.org/plugins/wp-pagenavi/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-pagenavi/</a>\nThis makes life easier :) Once you install this plugin, you can add this code to a custom page template, archive pages, category page in your theme.</p>\n\n<pre><code> <?php\n $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n $query_args = array(\n 'post_type' => 'post', //custom post type as well\n 'posts_per_page' => 5, //number of posts per page\n 'paged' => $paged,\n 'cat' => $catID, //category ID\n );\n $magic_all_posts_query = new WP_Query( $query_args );\n ?> \n <?php\n if ( $cn_all_posts_query->have_posts() ) : while ( $magic_all_posts_query->have_posts() ) : $cn_all_posts_query->the_post();\n ?>\n <div class=\"entry-single <?php echo $class ?>\">\n <h1 class=\"entry-title\">\n <a href=\"<?php the_permalink() ?>\">\n <?php the_title(); ?>\n </a>\n </h1>\n <div class=\"entry-content\">\n <?php\n $content = get_the_content();\n ?>\n </div>\n </div>\n <?php endwhile;\n wp_pagenavi( array( 'query' => $cn_all_posts_query ) );\n ?>\n</code></pre>\n\n<p>Do let us know if you run into any roadblocks with this.</p>\n"
},
{
"answer_id": 260725,
"author": "Sergey Serduk",
"author_id": 115822,
"author_profile": "https://wordpress.stackexchange.com/users/115822",
"pm_score": 2,
"selected": true,
"text": "<p>it's been a long time, I had exact the same task and here is the solution</p>\n\n<pre><code>$from = ($query->query_vars['posts_per_page'] * $paged) - ($query->query_vars['posts_per_page'] - 1);\nif(($query->query_vars['posts_per_page'] * $paged) <= ($query->found_posts)){\n $to = ($query->query_vars['posts_per_page'] * $paged);\n}else{\n $to = $query->found_posts;\n}\nif($from == $to){\n $from_to = $from;\n}else{\n $from_to = $from.' - '.$to;\n}\n</code></pre>\n\n<p>It's not the perfect code, but it works in most of situation.\nHave a nice day!)</p>\n"
},
{
"answer_id": 316465,
"author": "Luis Rivera",
"author_id": 126374,
"author_profile": "https://wordpress.stackexchange.com/users/126374",
"pm_score": 2,
"selected": false,
"text": "<p>If you are working with the default WP_Query you can do something like in your loop:</p>\n\n<pre><code>if ( have_posts() ) {\n global $wp_query;\n $paged = !empty($wp_query->query_vars['paged']) ? $wp_query->query_vars['paged'] : 1;\n $prev_posts = ( $paged - 1 ) * $wp_query->query_vars['posts_per_page'];\n $from = 1 + $prev_posts;\n $to = count( $wp_query->posts ) + $prev_posts;\n $of = $wp_query->found_posts;\n\n // ... Display the information, for example\n printf( '%s to %s of %s', $from, $to, $of );\n\n // Then your normal loop\n while ( have_posts() ) {\n //...\n }\n}\n</code></pre>\n\n<p>If you are working with a custom query you could do it like this:</p>\n\n<pre><code>$myquery = new WP_Query($yourqueryargs);\nif ( $myquery->have_posts() ) {\n $paged = !empty($myquery->query_vars['paged']) ? $myquery->query_vars['paged'] : 1;\n $prev_posts = ( $paged - 1 ) * $myquery->query_vars['posts_per_page'];\n $from = 1 + $prev_posts;\n $to = count( $myquery->posts ) + $prev_posts;\n $of = $myquery->found_posts;\n\n // ... Display the information, for example\n printf( '%s to %s of %s', $from, $to, $of );\n\n // Then your normal loop\n while ( have_posts() ) {\n //...\n }\n}\n</code></pre>\n\n<p><strong>Even better</strong> - Create a function that you can use either with the global $wp_query or with any custom query.</p>\n\n<pre><code>function myThemePostsNow ( $query = null ) {\n global $wp_query;\n\n if ( isset($query) && !($query instanceof WP_Query) ) {\n return; // Cancel if a query has been set and is not a WP_Query instance\n }\n elseif ( !isset($query) ) {\n $query = $wp_query; // If $query is not set, use global $wp_query data\n }\n\n if ( ! $query->have_posts() ) {\n return; // Cancel if $query don't have posts\n }\n\n // If we made it here it means we have a WP_Query with posts\n\n $paged = !empty($query->query_vars['paged']) ? $query->query_vars['paged'] : 1;\n $prev_posts = ( $paged - 1 ) * $query->query_vars['posts_per_page'];\n $from = 1 + $prev_posts;\n $to = count( $query->posts ) + $prev_posts;\n $of = $query->found_posts;\n\n // Return the information\n return sprintf( '%s to %s of %s', $from, $to, $of );\n}\n</code></pre>\n\n<p>Then just call your function</p>\n\n<pre><code>if ( have_posts() ) {\n\n echo myThemePostsNow();\n\n while ( have_posts() ) {\n //...\n }\n}\n</code></pre>\n\n<p>or in a custom query like:</p>\n\n<pre><code>if ( $myquery->have_posts() ) {\n\n echo myThemePostsNow();\n\n // Then your normal loop\n while ( have_posts() ) {\n //...\n }\n}\n</code></pre>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10692/"
] |
I know I'm doing something that's been done 1000's of times before in WordPress, but struggling to get the terms to find it on the Interwebs.
I've got a custom category template page and have a while loop that shows the first 5 results (of which there are more than 5).
How do I output something within my while that shows the relative position in the results and the total number:
I know how to get the post count:
```
<?php
$catcount = new WP_Query( 'cat=4&posts_per_page=-1' );
?>
```
But not sure how to setup the pagination and the relative results, meaning
Results 1-10 of `<?php echo $total->found_posts; ?>`
How do I get the results values 1 of 2 and then create pagination for subsequent pages?
|
it's been a long time, I had exact the same task and here is the solution
```
$from = ($query->query_vars['posts_per_page'] * $paged) - ($query->query_vars['posts_per_page'] - 1);
if(($query->query_vars['posts_per_page'] * $paged) <= ($query->found_posts)){
$to = ($query->query_vars['posts_per_page'] * $paged);
}else{
$to = $query->found_posts;
}
if($from == $to){
$from_to = $from;
}else{
$from_to = $from.' - '.$to;
}
```
It's not the perfect code, but it works in most of situation.
Have a nice day!)
|
202,457 |
<p>I have modified the comment query arguments in <code>comment-template.php</code> from </p>
<pre><code>$author_id = get_query_var( 'author_id', 1 );
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
);
$comments = get_comments( $comment_args );
</code></pre>
<p>to the following code below</p>
<pre><code>$author_id = get_query_var( 'author_id', 1 );
if($author_id == '') {
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
);
}
else {
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
'meta_key' => 'custom_author_id',
'meta_value'=> $author_id,
);
}
$comments = get_comments( $comment_args );
</code></pre>
<p>I would like to know how to modify the number of comments being diplayed i.e. <code>get_comments_number()</code></p>
|
[
{
"answer_id": 202464,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p><code>get_comments_number()</code> does not rely on any comment query, it simply reports the number of comments stored persistently in post object (<code>comment_count</code> property).</p>\n\n<p>You have omitted in your example how exactly query itself looks like. If you are using actual <code>WP_Comment_Query</code> object then its <code>comments</code> property will have array of results you could <code>count()</code>. If using API functions might get messier than that.</p>\n"
},
{
"answer_id": 202471,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<h3>Refrain from editing core files</h3>\n<p>WordPress was developed with extensibility in mind, and provides many ways to change the appearance and functionality of an installation without altering the WordPress software itself (mostly using <a href=\"https://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters\" rel=\"nofollow noreferrer\">Hooks</a> in conjunction with <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">Plugins</a> and <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">Themes</a>). The software is comprised of it's "core files", which are generally everything outside of the <code>./wp-content</code> directory except <code>./wp-config.php</code>, and any directory-level server configuration files (<code>.htaccess</code>, etc.).</p>\n<p>Editing the core files of a WordPress installation is typically neither necessary nor maintainable, and as such is <em><strong>strongly</strong></em> discouraged unless you can find no other means to achieve your ends and are familiar with the consequences of doing so; these include automatic updates overwriting your changes, the WordPress community largely offering no support for your changes, and perhaps most importantly, <strong>you run a much larger risk of introducing new security vulnerabilities into your WordPress installation</strong>.</p>\n</blockquote>\n<p>Rather than altering the core file <a href=\"https://core.trac.wordpress.org/browser/tags/4.3/src/wp-includes/comment-template.php#L1113\" rel=\"nofollow noreferrer\"><code>./wp-includes/comment-template.php</code></a>, a more maintainable solution would be to create <a href=\"https://codex.wordpress.org/Theme_Development#Comments_.28comments.php.29\" rel=\"nofollow noreferrer\">a <code>comments.php</code> template file</a> within your custom theme (or <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">a child theme</a> of your current theme if was developed by a third-party) and use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Comment_Query\" rel=\"nofollow noreferrer\">WP_Comment_Query</a> in it to specify your new arguments. Use the <code>number</code> and <code>offset</code> arguments to specify a desired range of comments.</p>\n<p><strong>Template File <code>./wp-content/themes/wpse202457_theme/comments.php</code>:</strong></p>\n<pre><code><?php\n $author_id = get_query_var( 'author_id', '' );\n $comments = array();\n\n if( $author_id != '' ) {\n $comment_args = array(\n 'order' => 'ASC',\n 'orderby' => 'comment_date_gmt',\n 'status' => 'approve',\n 'meta_key' => 'custom_author_id',\n 'meta_value' => $author_id,\n 'number' => 20, // Retrieve 20 comments...\n 'offset' => 40 // ...starting from the 40th comment.\n );\n \n $comment_query = new WP_Comment_Query;\n $comments = $comment_query->query( $comment_args );\n }\n \n \n if( ! empty( $comments ) ) {\n // The Comments Loop\n foreach( $comments as $comment ) {\n echo( '<p>' . $comment->comment_content . '</p><br/><br/>' );\n }\n }\n else {\n echo( '<p>No comments found</p>' );\n }\n?>\n</code></pre>\n<p>Check out <a href=\"https://wordpress.stackexchange.com/questions/184449/wp-comment-query-pagination-delving-into-the-unknown\">this excellent question</a> for the way to handle breaking comments up into pages (pagination) using the <code>number</code> and <code>offset</code> arguments dynamically. Dig into other themes' <code>comments.php</code> template file for some example markup.</p>\n<p>Instead of creating a new theme template, you could alternately place your substitute comments template in a plugin, and use the <a href=\"https://codex.wordpress.org/Function_Reference/comments_template\" rel=\"nofollow noreferrer\"><code>comments_template</code> filter</a> to redirect comment template inclusions to it:</p>\n<p><strong>Plugin File <code>./wp-content/plugins/wpse202457_comments_plugin/wpse202457CommentsPlugin.php</code>:</strong></p>\n<pre><code>function wpse202457_comments_template( $comment_template ) {\n // Redirect ALL comment template inclusions to "./wp-content/plugins/wpse202457_comments_plugin/comments.php"\n return dirname(__FILE__) . '/comments.php';\n}\n\nadd_filter( 'comments_template', 'wpse202457_comments_template' );\n</code></pre>\n<hr />\n<h2>ADDENDUM</h2>\n<p>In response to the comments, as @Rarst suggested, the <code>get_comments_query()</code> function will only return the number of comments recorded for the post object displayed in the main query.</p>\n<p>To get the number of comments for your altered query, simply <code>count()</code> the results of the query, i.e.:</p>\n<pre><code>$comment_query = new WP_Comment_Query;\n$comments = $comment_query->query( $comment_args );\n$comment_count = count( $comments );\n</code></pre>\n<p><strong>However</strong>, if you are using the <code>number</code> argument to specify the number of comments you wish to retrieve, then <code>$comment_count</code> will always be equal to, or less than <code>number</code>. To get the total number of comments that match your arguments, you will either need to omit the <code>number</code> argument and <code>count()</code> the results, or set the <code>count</code> argument to <code>true</code>, in which case the query will return the number of matching comments without returning the comments themselves:</p>\n<pre><code>$author_id = get_query_var( 'author_id', 1 );\n$comment_args = array(\n 'status' => 'approve',\n 'meta_key' => 'custom_author_id',\n 'meta_value' => $author_id,\n 'count' => true // Return the NUMBER of matching comments, not the matching comment objects themselves\n);\n\n$comment_query = new WP_Comment_Query;\n$comment_count = $comment_query->query( $comment_args );\n</code></pre>\n<p>If you don't plan on doing anything else with the <code>WP_Comment_Query</code> object, you may want to create some convenience functions and put them in your plugin, or your custom theme's <code>functions.php</code> for quick access. Something along the lines of:</p>\n<pre><code>// Get comments with a custom_author_id meta-value of $author_id\nfunction wpse202471_get_author_comments( $author_id = null, $args = array() ) {\n // If an author id was not passed, see if there's one in the query vars\n if( ! isset( $author_id ) )\n $author_id = get_query_var( 'author_id', null );\n\n // If no author id was provided, return a negative result\n if( ! isset( $author_id ) ) {\n if( isset( $args[ 'count' ] ) && $args[ 'count' ] )\n return 0;\n\n return array();\n }\n\n // Merge query argument arrays\n $comment_args = array_merge(\n array( // Default values\n 'order' => 'ASC',\n 'orderby' => 'comment_date_gmt',\n 'status' => 'approve'\n ),\n $args, // Any arguments passed to the function\n array( // Merge meta-arguments last, so nothing can overwrite them\n 'meta_key' => 'custom_author_id',\n 'meta_value' => $author_id\n )\n );\n\n // Perform the query and return the results\n $comment_query = new WP_Comment_Query;\n return $comment_query->query( $comment_args );\n}\n\n// Get the total number of comments with a custom_author_id meta-value of $author_id\nfunction wpse202471_get_author_comment_count( $author_id = null, $args = array() ) {\n $args[ 'count' ] = true;\n \n // Remove query arguments that would prevent the proper count from being returned\n if( isset( $args[ 'number' ] ) )\n unset( $args[ 'number' ] );\n\n if( isset( $args[ 'offset' ] ) )\n unset( $args[ 'offset' ] );\n\n return wpse202471_get_author_comments( $author_id, $args );\n}\n</code></pre>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
I have modified the comment query arguments in `comment-template.php` from
```
$author_id = get_query_var( 'author_id', 1 );
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
);
$comments = get_comments( $comment_args );
```
to the following code below
```
$author_id = get_query_var( 'author_id', 1 );
if($author_id == '') {
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
);
}
else {
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
'meta_key' => 'custom_author_id',
'meta_value'=> $author_id,
);
}
$comments = get_comments( $comment_args );
```
I would like to know how to modify the number of comments being diplayed i.e. `get_comments_number()`
|
>
> ### Refrain from editing core files
>
>
> WordPress was developed with extensibility in mind, and provides many ways to change the appearance and functionality of an installation without altering the WordPress software itself (mostly using [Hooks](https://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters) in conjunction with [Plugins](https://codex.wordpress.org/Writing_a_Plugin) and [Themes](https://codex.wordpress.org/Theme_Development)). The software is comprised of it's "core files", which are generally everything outside of the `./wp-content` directory except `./wp-config.php`, and any directory-level server configuration files (`.htaccess`, etc.).
>
>
> Editing the core files of a WordPress installation is typically neither necessary nor maintainable, and as such is ***strongly*** discouraged unless you can find no other means to achieve your ends and are familiar with the consequences of doing so; these include automatic updates overwriting your changes, the WordPress community largely offering no support for your changes, and perhaps most importantly, **you run a much larger risk of introducing new security vulnerabilities into your WordPress installation**.
>
>
>
Rather than altering the core file [`./wp-includes/comment-template.php`](https://core.trac.wordpress.org/browser/tags/4.3/src/wp-includes/comment-template.php#L1113), a more maintainable solution would be to create [a `comments.php` template file](https://codex.wordpress.org/Theme_Development#Comments_.28comments.php.29) within your custom theme (or [a child theme](https://codex.wordpress.org/Child_Themes) of your current theme if was developed by a third-party) and use [WP\_Comment\_Query](https://codex.wordpress.org/Class_Reference/WP_Comment_Query) in it to specify your new arguments. Use the `number` and `offset` arguments to specify a desired range of comments.
**Template File `./wp-content/themes/wpse202457_theme/comments.php`:**
```
<?php
$author_id = get_query_var( 'author_id', '' );
$comments = array();
if( $author_id != '' ) {
$comment_args = array(
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve',
'meta_key' => 'custom_author_id',
'meta_value' => $author_id,
'number' => 20, // Retrieve 20 comments...
'offset' => 40 // ...starting from the 40th comment.
);
$comment_query = new WP_Comment_Query;
$comments = $comment_query->query( $comment_args );
}
if( ! empty( $comments ) ) {
// The Comments Loop
foreach( $comments as $comment ) {
echo( '<p>' . $comment->comment_content . '</p><br/><br/>' );
}
}
else {
echo( '<p>No comments found</p>' );
}
?>
```
Check out [this excellent question](https://wordpress.stackexchange.com/questions/184449/wp-comment-query-pagination-delving-into-the-unknown) for the way to handle breaking comments up into pages (pagination) using the `number` and `offset` arguments dynamically. Dig into other themes' `comments.php` template file for some example markup.
Instead of creating a new theme template, you could alternately place your substitute comments template in a plugin, and use the [`comments_template` filter](https://codex.wordpress.org/Function_Reference/comments_template) to redirect comment template inclusions to it:
**Plugin File `./wp-content/plugins/wpse202457_comments_plugin/wpse202457CommentsPlugin.php`:**
```
function wpse202457_comments_template( $comment_template ) {
// Redirect ALL comment template inclusions to "./wp-content/plugins/wpse202457_comments_plugin/comments.php"
return dirname(__FILE__) . '/comments.php';
}
add_filter( 'comments_template', 'wpse202457_comments_template' );
```
---
ADDENDUM
--------
In response to the comments, as @Rarst suggested, the `get_comments_query()` function will only return the number of comments recorded for the post object displayed in the main query.
To get the number of comments for your altered query, simply `count()` the results of the query, i.e.:
```
$comment_query = new WP_Comment_Query;
$comments = $comment_query->query( $comment_args );
$comment_count = count( $comments );
```
**However**, if you are using the `number` argument to specify the number of comments you wish to retrieve, then `$comment_count` will always be equal to, or less than `number`. To get the total number of comments that match your arguments, you will either need to omit the `number` argument and `count()` the results, or set the `count` argument to `true`, in which case the query will return the number of matching comments without returning the comments themselves:
```
$author_id = get_query_var( 'author_id', 1 );
$comment_args = array(
'status' => 'approve',
'meta_key' => 'custom_author_id',
'meta_value' => $author_id,
'count' => true // Return the NUMBER of matching comments, not the matching comment objects themselves
);
$comment_query = new WP_Comment_Query;
$comment_count = $comment_query->query( $comment_args );
```
If you don't plan on doing anything else with the `WP_Comment_Query` object, you may want to create some convenience functions and put them in your plugin, or your custom theme's `functions.php` for quick access. Something along the lines of:
```
// Get comments with a custom_author_id meta-value of $author_id
function wpse202471_get_author_comments( $author_id = null, $args = array() ) {
// If an author id was not passed, see if there's one in the query vars
if( ! isset( $author_id ) )
$author_id = get_query_var( 'author_id', null );
// If no author id was provided, return a negative result
if( ! isset( $author_id ) ) {
if( isset( $args[ 'count' ] ) && $args[ 'count' ] )
return 0;
return array();
}
// Merge query argument arrays
$comment_args = array_merge(
array( // Default values
'order' => 'ASC',
'orderby' => 'comment_date_gmt',
'status' => 'approve'
),
$args, // Any arguments passed to the function
array( // Merge meta-arguments last, so nothing can overwrite them
'meta_key' => 'custom_author_id',
'meta_value' => $author_id
)
);
// Perform the query and return the results
$comment_query = new WP_Comment_Query;
return $comment_query->query( $comment_args );
}
// Get the total number of comments with a custom_author_id meta-value of $author_id
function wpse202471_get_author_comment_count( $author_id = null, $args = array() ) {
$args[ 'count' ] = true;
// Remove query arguments that would prevent the proper count from being returned
if( isset( $args[ 'number' ] ) )
unset( $args[ 'number' ] );
if( isset( $args[ 'offset' ] ) )
unset( $args[ 'offset' ] );
return wpse202471_get_author_comments( $author_id, $args );
}
```
|
202,463 |
<p>Among WordPress' <a href="https://codex.wordpress.org/Roles_and_Capabilities" rel="noreferrer">capabilities</a> are <code>unfiltered_html</code> and <code>unfiltered_upload</code>, however I have yet to find any documentation about what specifically they allow or prevent in their filtering. </p>
<p>The only mention I've found on WordPress' site about <code>unfiltered_html</code> is:</p>
<blockquote>
<p>Allows user to post HTML markup or even JavaScript code in pages,
posts, comments and widgets.</p>
</blockquote>
<p>I've seen that JavaScript is filtered out for non-admins, but what HTML is being filtered? </p>
<p>And for <code>unfiltered_upload</code>:</p>
<blockquote>
<p>This capability is not available to any role by default (including
Super Admins). The capability needs to be enabled by defining the
following constant:</p>
<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );
</code></pre>
<p>With this constant defined, all roles on a single site install can be
given the unfiltered_upload capability, but only Super Admins can be
given the capability on a Multisite install.</p>
</blockquote>
<p>And again, the description doesn't spell out what's permitted and what's filtered out. </p>
<p>Can someone tell me exactly what elements, code, or file types the <code>unfiltered_html</code> and <code>unfiltered_upload</code> capabilities allow or prevent?</p>
|
[
{
"answer_id": 202465,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": false,
"text": "<p>It is hard to come up with <em>precise</em> answer since capabilities are often used more broadly than they imply. For example check for <code>manage_options</code> is usually synonym to check for admin user and can come up in contexts that don't actually have much to do with <em>options</em>.</p>\n\n<p><em>Usually</em> it will be a difference between subject content passing or not passing through <a href=\"https://codex.wordpress.org/Function_Reference/wp_kses\"><code>wp_kses()</code></a>. Specific kses settings and what is considered allowed would depend on the context and might wary.</p>\n\n<p>For <code>unfiltered_upload</code> as far as I remember it's more straightforward. Without it only white listed file types are allowed. The list is based on <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_mime_types\"><code>wp_get_mime_types()</code></a>.</p>\n"
},
{
"answer_id": 274846,
"author": "John Le Fevre",
"author_id": 124683,
"author_profile": "https://wordpress.stackexchange.com/users/124683",
"pm_score": 2,
"selected": false,
"text": "<p>I appreciate this is an old thread, but restricted unfiltered_html was causing us huge problems on our news site. </p>\n\n<p>The in-house writers (a special class of user) are required to place photos and videos in their story. While photos are not a problem, embedding iframe's into the page with the video code embedded saw the embedded code vanish when they saved their stories. </p>\n\n<p>If the video was embedded for them by an editor the writers would still lose the iframe when they saved their stories. </p>\n\n<p>By unblocking unfiltered_html our staff writers can embed the video content and lay up their post properly. </p>\n\n<p>As for unfiltered_uploads, I belie that has been answered. </p>\n\n<p>Hope this helps someone. </p>\n"
},
{
"answer_id": 382480,
"author": "Edoardo Guzzi",
"author_id": 190590,
"author_profile": "https://wordpress.stackexchange.com/users/190590",
"pm_score": 0,
"selected": false,
"text": "<p>unfiltered_html in network</p>\n<p>These capabilities block the possibility for all users except super admins to insert JavaScript iframe code etc. in WordPress pages or posts and if one of them(admin, editor ECC) edits a page with an active iframe or JS it is removed.</p>\n<p>To give administrators the possibility to add such codes, these abilities must be enabled and to do so you can use this plugin</p>\n<p><a href=\"https://wordpress.org/plugins/unfiltered-mu/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/unfiltered-mu/</a></p>\n"
}
] |
2015/09/11
|
[
"https://wordpress.stackexchange.com/questions/202463",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26666/"
] |
Among WordPress' [capabilities](https://codex.wordpress.org/Roles_and_Capabilities) are `unfiltered_html` and `unfiltered_upload`, however I have yet to find any documentation about what specifically they allow or prevent in their filtering.
The only mention I've found on WordPress' site about `unfiltered_html` is:
>
> Allows user to post HTML markup or even JavaScript code in pages,
> posts, comments and widgets.
>
>
>
I've seen that JavaScript is filtered out for non-admins, but what HTML is being filtered?
And for `unfiltered_upload`:
>
> This capability is not available to any role by default (including
> Super Admins). The capability needs to be enabled by defining the
> following constant:
>
>
>
> ```
> define( 'ALLOW_UNFILTERED_UPLOADS', true );
>
> ```
>
> With this constant defined, all roles on a single site install can be
> given the unfiltered\_upload capability, but only Super Admins can be
> given the capability on a Multisite install.
>
>
>
And again, the description doesn't spell out what's permitted and what's filtered out.
Can someone tell me exactly what elements, code, or file types the `unfiltered_html` and `unfiltered_upload` capabilities allow or prevent?
|
It is hard to come up with *precise* answer since capabilities are often used more broadly than they imply. For example check for `manage_options` is usually synonym to check for admin user and can come up in contexts that don't actually have much to do with *options*.
*Usually* it will be a difference between subject content passing or not passing through [`wp_kses()`](https://codex.wordpress.org/Function_Reference/wp_kses). Specific kses settings and what is considered allowed would depend on the context and might wary.
For `unfiltered_upload` as far as I remember it's more straightforward. Without it only white listed file types are allowed. The list is based on [`wp_get_mime_types()`](https://codex.wordpress.org/Function_Reference/wp_get_mime_types).
|
202,487 |
<p>I have a simple table layout as per below:</p>
<pre><code><table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</table>
</code></pre>
<p>And the following CSS:</p>
<pre><code>table td:nth-child(1),
table tr:nth-child(1) {
font-weight: bold;
}
</code></pre>
<p>The first column is bolded but the first row remains as normal text. I don't want to use headers as TinyMCE in Wordpress creates tables automatically in the above format so I'd rather just stick with that rather than then have to change the HTML.</p>
<p>Incidentally, the following does work so I assume there is no issue using "tr:nth-child(n)"</p>
<pre><code>tbody tr:nth-child(odd) {
background: #eee;
}
</code></pre>
<p>Would appreciate your help.</p>
|
[
{
"answer_id": 202495,
"author": "Tom Berghuis",
"author_id": 63473,
"author_profile": "https://wordpress.stackexchange.com/users/63473",
"pm_score": -1,
"selected": false,
"text": "<pre><code>table:nth-child(1),\ntable tr:nth-child(1) {\n font-weight: bold;\n}\n</code></pre>\n"
},
{
"answer_id": 202542,
"author": "Gecko Boy",
"author_id": 62598,
"author_profile": "https://wordpress.stackexchange.com/users/62598",
"pm_score": 0,
"selected": false,
"text": "<p>After much frustration I realised that the issue is the fact that you need ultimately to specify what you do with the <strong>cell</strong> in the nth row, hence the correct code is:</p>\n\n<pre><code>table td:nth-child(1),\ntable tr:nth-child(1) td {\n font-weight: bold;\n}\n</code></pre>\n\n<p>Putting this up as the answer as there are a lot of sources that use the header to style the top row but don't stipulate what needs to be done if you have a table layout without a header.</p>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62598/"
] |
I have a simple table layout as per below:
```
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</table>
```
And the following CSS:
```
table td:nth-child(1),
table tr:nth-child(1) {
font-weight: bold;
}
```
The first column is bolded but the first row remains as normal text. I don't want to use headers as TinyMCE in Wordpress creates tables automatically in the above format so I'd rather just stick with that rather than then have to change the HTML.
Incidentally, the following does work so I assume there is no issue using "tr:nth-child(n)"
```
tbody tr:nth-child(odd) {
background: #eee;
}
```
Would appreciate your help.
|
After much frustration I realised that the issue is the fact that you need ultimately to specify what you do with the **cell** in the nth row, hence the correct code is:
```
table td:nth-child(1),
table tr:nth-child(1) td {
font-weight: bold;
}
```
Putting this up as the answer as there are a lot of sources that use the header to style the top row but don't stipulate what needs to be done if you have a table layout without a header.
|
202,489 |
<p>In a website I am working on ,there are 50 categories + sub categories, each has a a <strong>very long</strong> description text, then in an archive page I display all the titles of the categories + their description ,but it makes more sense to show the title of each category + a few words of each description (excerpt?) and a "read more" link ,to the full content of that category .</p>
<p>so I have read the codex and also a lot of articles on the Web, but still I cant understand the reason why this sort of functionality doesn't exist in WordPress by default.
It exists only for posts -Function Reference/the excerpt.</p>
<p>Second question is what is the most elegant way to solve it ?</p>
<p>There are a few plugins or snippets of code that enable you to add html editor to the category description in the admin side, but selecting the read more link doesnt work there:(</p>
<p>Is the only solution to write a very long Hook/filter on the category_description() function ?</p>
<p>to elaborate: this is my code in category.php , - what is does is diplaying the parent category and all its children(titles+ full descriptions)</p>
<pre><code> <?php
$CategoryPar = get_category( get_query_var( 'cat' ) );
$cat_id = $CategoryPar->cat_ID;
$args = array(
'orderby' => 'name',
'child_of' => $cat_id,
'hide_empty' => FALSE,
'order' => 'ASC'
);
$Ecategories = get_categories($args);
echo'<div class="cat-sub-title">';
foreach($Ecategories as $Ecategory) {
echo '<p><a href="' . get_category_link( $Ecategory->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $Ecategory->name ) . '" ' . '>' . $Ecategory->name.'</a> </p> ';
echo '<div class="cat-sub-title-desc">'. $Ecategory->description . '</div>';
}
echo'</div>';
?>
</code></pre>
|
[
{
"answer_id": 202491,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>I've been looking for a filter for <code>category_description()</code> and I have not found any. You could use <code>wp_trim_words()</code> with <code>category_description()</code> to get the desired result. For example:</p>\n\n<pre><code>$cat_ID = 4;\n\n// wp_trim_words( $text, $num_words = 55, $more = null );\necho wp_trim_words( category_description( $cat_ID ), 55, '<a href=\"' . get_category_link( $cat_ID ) . '\">' . __(\"Read more\", \"text-domain\" ) . '</a>' );\n</code></pre>\n\n<h2>Update: I've found the filter</h2>\n\n<pre><code>add_filter( 'category_description', 'cyb_trim_category_desc', 10, 2 );\nfunction cyb_trim_category_desc( $desc, $cat_id ) {\n\n // wp_trim_words( $text, $num_words = 55, $more = null );\n $desc = wp_trim_words( $desc, 55, '<a href=\"' . get_category_link( $cat_id ) . '\">' . __(\"Read more\", \"text-domain\" ) . '</a>' );\n\n return $desc;\n}\n</code></pre>\n\n<p><strong>Note</strong>: if you use the generic <code>the_archive_description()</code> function in your theme, the above filter works perfectly for categories archvie.</p>\n"
},
{
"answer_id": 402797,
"author": "stiviniii",
"author_id": 192541,
"author_profile": "https://wordpress.stackexchange.com/users/192541",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the solution that worked on my end using jquery pasted this code on function.php file. this is only if you want to truncate the description of your category page on woocommerce.</p>\n<pre><code>/**\n * @snippet Truncate Short Description @ WooCommerce category description\n * @author Steve Ayo\n */\n \n\n \nadd_action( 'woocommerce_after_main_content', 'bbloomer_woocommerce_short_description_truncate_read_more' );\n \nfunction bbloomer_woocommerce_short_description_truncate_read_more() { \n wc_enqueue_js('\n var show_char = 300;\n var ellipses = "... ";\n var content = $(".term-description").html();\n if (content.length > show_char) {\n var a = content.substr(0, show_char);\n var b = content.substr(show_char - content.length);\n var html = a + "<span class=\\'truncated\\' style=\\'display:none\\'>" + b + "</span> <span class=\\'truncated-expander\\'>" + ellipses + "<a href=\\'#\\' class=\\'read-more\\'>Read more</a></span>";\n $(".term-description").html(html);\n }\n $(".read-more").click(function(e) {\n e.preventDefault();\n $(".term-description .truncated").toggle();\n if($(".term-description .truncated").is(":visible")){\n $(".read-more").text("Show Less")\n } else{\n $(".read-more").text("Read More")\n }\n });\n\n ');\n}\n</code></pre>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51370/"
] |
In a website I am working on ,there are 50 categories + sub categories, each has a a **very long** description text, then in an archive page I display all the titles of the categories + their description ,but it makes more sense to show the title of each category + a few words of each description (excerpt?) and a "read more" link ,to the full content of that category .
so I have read the codex and also a lot of articles on the Web, but still I cant understand the reason why this sort of functionality doesn't exist in WordPress by default.
It exists only for posts -Function Reference/the excerpt.
Second question is what is the most elegant way to solve it ?
There are a few plugins or snippets of code that enable you to add html editor to the category description in the admin side, but selecting the read more link doesnt work there:(
Is the only solution to write a very long Hook/filter on the category\_description() function ?
to elaborate: this is my code in category.php , - what is does is diplaying the parent category and all its children(titles+ full descriptions)
```
<?php
$CategoryPar = get_category( get_query_var( 'cat' ) );
$cat_id = $CategoryPar->cat_ID;
$args = array(
'orderby' => 'name',
'child_of' => $cat_id,
'hide_empty' => FALSE,
'order' => 'ASC'
);
$Ecategories = get_categories($args);
echo'<div class="cat-sub-title">';
foreach($Ecategories as $Ecategory) {
echo '<p><a href="' . get_category_link( $Ecategory->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $Ecategory->name ) . '" ' . '>' . $Ecategory->name.'</a> </p> ';
echo '<div class="cat-sub-title-desc">'. $Ecategory->description . '</div>';
}
echo'</div>';
?>
```
|
I've been looking for a filter for `category_description()` and I have not found any. You could use `wp_trim_words()` with `category_description()` to get the desired result. For example:
```
$cat_ID = 4;
// wp_trim_words( $text, $num_words = 55, $more = null );
echo wp_trim_words( category_description( $cat_ID ), 55, '<a href="' . get_category_link( $cat_ID ) . '">' . __("Read more", "text-domain" ) . '</a>' );
```
Update: I've found the filter
-----------------------------
```
add_filter( 'category_description', 'cyb_trim_category_desc', 10, 2 );
function cyb_trim_category_desc( $desc, $cat_id ) {
// wp_trim_words( $text, $num_words = 55, $more = null );
$desc = wp_trim_words( $desc, 55, '<a href="' . get_category_link( $cat_id ) . '">' . __("Read more", "text-domain" ) . '</a>' );
return $desc;
}
```
**Note**: if you use the generic `the_archive_description()` function in your theme, the above filter works perfectly for categories archvie.
|
202,496 |
<p>I run a small site based on wp with user generated content. Users often submit youtube links. And then wordpress automatically converts these links to videos which is <strong>unwanted in our case</strong>. I need to override this automatic behavior so that the submitted youtube links remains in <code>plain text urls</code> ?</p>
<p>I found out that I could <a href="https://codex.wordpress.org/Function_Reference/wp_oembed_remove_provider" rel="nofollow">remove the oembed provider</a> itself with something like <code>wp_oembed_remove_provider('http://www.youtube.com/oembed')</code> but I am stumped at how do I use this in my case where <code>$content</code> is the string that contains the url as well as the submitted post content ? The <a href="https://codex.wordpress.org/Function_Reference/wp_oembed_remove_provider" rel="nofollow">codex page</a> doesnot says much about it. Could someone give me an example of how this can be done.</p>
<p>In other words I need the oEmbed to skip any youtube link/s in content. Also please let me know if there is a better/more efficient way of solving this.</p>
|
[
{
"answer_id": 202497,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 3,
"selected": true,
"text": "<p>disable the oembed like below in functions.php :</p>\n\n<pre><code>remove_filter( 'the_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 );\n</code></pre>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 208065,
"author": "Chris Montgomery",
"author_id": 18050,
"author_profile": "https://wordpress.stackexchange.com/users/18050",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer didn't work in my case. URLs were still being converted to embeds in the post editor.</p>\n\n<p>By looking at the source of <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/class-wp-embed.php#L23\" rel=\"noreferrer\">wp-includes/class-wp-embed.php</a> where this stuff is handled, I found that there are some other things at play here:</p>\n\n<pre><code>// Hack to get the [embed] shortcode to run before wpautop()\nadd_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );\n\n// Shortcode placeholder for strip_shortcodes()\nadd_shortcode( 'embed', '__return_false' );\n\n// Attempts to embed all URLs in a post\nadd_filter( 'the_content', array( $this, 'autoembed' ), 8 );\n\n// After a post is saved, cache oEmbed items via AJAX\nadd_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );\n</code></pre>\n\n<p>What fixed the issue for me was disabling these in my theme files like so:</p>\n\n<pre><code>remove_shortcode( 'embed' );\nremove_filter( 'the_content', [ $GLOBALS['wp_embed'], 'autoembed' ], 8 );\nremove_filter( 'the_content', [ $GLOBALS['wp_embed'], 'run_shortcode' ], 8 );\nremove_action( 'edit_form_advanced', [ $GLOBALS['wp_embed'], 'maybe_run_ajax_cache' ] );\n</code></pre>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25508/"
] |
I run a small site based on wp with user generated content. Users often submit youtube links. And then wordpress automatically converts these links to videos which is **unwanted in our case**. I need to override this automatic behavior so that the submitted youtube links remains in `plain text urls` ?
I found out that I could [remove the oembed provider](https://codex.wordpress.org/Function_Reference/wp_oembed_remove_provider) itself with something like `wp_oembed_remove_provider('http://www.youtube.com/oembed')` but I am stumped at how do I use this in my case where `$content` is the string that contains the url as well as the submitted post content ? The [codex page](https://codex.wordpress.org/Function_Reference/wp_oembed_remove_provider) doesnot says much about it. Could someone give me an example of how this can be done.
In other words I need the oEmbed to skip any youtube link/s in content. Also please let me know if there is a better/more efficient way of solving this.
|
disable the oembed like below in functions.php :
```
remove_filter( 'the_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 );
```
Thanks!
|
202,500 |
<p>I'm trying to output the values of two custom fields created by ACF plugin in a custom post type. I actually need this to be displayed in a popup window. wordpress popup plugins don't support php code, only shortcodes can be called from the content editor. So I'm trying to create a shortcode to be used in the editor of the popup to display the values of the custom fields.
I know that we can generate shortcode <code>[cite]</code> using this code in theme functions.php</p>
<pre><code>function cite_shortcode() {
}
add_shortcode( 'cite', 'cite_shortcode' );
</code></pre>
<p>But i couldn't figure out how to add the php code to that code. I tried to do something like:</p>
<pre><code>function cite_shortcode() {
<div>
<?php
$object_terms = wp_get_object_terms( $post->ID, 'issue', array( 'fields' => 'all' ) );
if ( $object_terms ) {
$res = '';
foreach ( $object_terms as $term ) {
if ( $term->parent ) {
$res .= $term->name . ', ';
}
}
echo rtrim($res,' ,');
}
?>), pp: <?php the_field('first_page'); ?>-<?php the_field('last_page'); ?>
</div>
}
add_shortcode( 'cite', 'cite_shortcode' );
</code></pre>
<p>But it didn't work. it shows:</p>
<blockquote>
<p>Parse error: syntax error, unexpected</p>
</blockquote>
<p>So, my questions are:</p>
<ol>
<li>how can i make that code work?</li>
<li>is it possible to put the php code in cite.php file and output its values via a shortcode generated in functions.php? and how to do that?</li>
</ol>
<p>Best regards</p>
|
[
{
"answer_id": 270084,
"author": "BigDropGR",
"author_id": 73164,
"author_profile": "https://wordpress.stackexchange.com/users/73164",
"pm_score": 0,
"selected": false,
"text": "<p>Just in case anyone will search for this in the future...</p>\n\n<p>The proper way to output php value through a shortcode is this one:</p>\n\n<pre><code>add_shortcode('shortcode_name', 'shortcode_callback');\nfunction shortcode_callback( $atts = array(), $content = null ) {\n\n $output = \"Add your PHP here!!!\";\n\n return $output;\n\n}\n</code></pre>\n\n<p>Greetings from sunny Greece!!!</p>\n"
},
{
"answer_id": 310539,
"author": "WPZA",
"author_id": 146181,
"author_profile": "https://wordpress.stackexchange.com/users/146181",
"pm_score": 1,
"selected": false,
"text": "<p>We've built shortcodes in the past using concatenating variables.</p>\n\n<p>To paraphrase the link above, you should output your PHP as such.</p>\n\n<pre><code> $output = '<p>';\n $output .= '<strong>' . $content . '</strong>';\n $output .= '</p>';\n return $output;\n</code></pre>\n\n<p>Note, see the <code>.=</code> variable concatenation.</p>\n"
},
{
"answer_id": 331248,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>how can i make that code work?</li>\n </ol>\n</blockquote>\n\n<pre><code>function cite_shortcode($atts) {\n $output = '<div>';\n\n $object_terms = wp_get_object_terms( $post->ID, 'issue', array( 'fields' => 'all' ) );\n\n if ( $object_terms ) {\n\n $res = '';\n\n foreach ( $object_terms as $term ) {\n\n if ( $term->parent ) { \n $res .= $term->name . ', '; \n }\n\n }\n\n $output .= rtrim($res,' ,'); \n }\n\n $output .= 'pp: '.get_the_field('first_page') . '-' . get_the_field('last_page');\n\n $output .= '</div>';\n\n return $output ;\n}\n\nadd_shortcode( 'cite', 'cite_shortcode' );\n</code></pre>\n\n<blockquote>\n <ol start=\"2\">\n <li>is it possible to put the php code in cite.php file and output its values via a shortcode generated in functions.php? and how to do that?</li>\n </ol>\n</blockquote>\n\n<p>In this case, you can inclde your php file within short code, something similar to this code </p>\n\n<pre><code>function cite_shortcode($atts) {\n $output = '';\n\n ob_start();\n\n include \"yourphpfile.php\"; // Replace with exact location of php file \n\n\n $output .= ob_get_clean();\n\n return $output ;\n}\n\nadd_shortcode( 'cite', 'cite_shortcode' );\n</code></pre>\n\n<p>I hope this helps.</p>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73173/"
] |
I'm trying to output the values of two custom fields created by ACF plugin in a custom post type. I actually need this to be displayed in a popup window. wordpress popup plugins don't support php code, only shortcodes can be called from the content editor. So I'm trying to create a shortcode to be used in the editor of the popup to display the values of the custom fields.
I know that we can generate shortcode `[cite]` using this code in theme functions.php
```
function cite_shortcode() {
}
add_shortcode( 'cite', 'cite_shortcode' );
```
But i couldn't figure out how to add the php code to that code. I tried to do something like:
```
function cite_shortcode() {
<div>
<?php
$object_terms = wp_get_object_terms( $post->ID, 'issue', array( 'fields' => 'all' ) );
if ( $object_terms ) {
$res = '';
foreach ( $object_terms as $term ) {
if ( $term->parent ) {
$res .= $term->name . ', ';
}
}
echo rtrim($res,' ,');
}
?>), pp: <?php the_field('first_page'); ?>-<?php the_field('last_page'); ?>
</div>
}
add_shortcode( 'cite', 'cite_shortcode' );
```
But it didn't work. it shows:
>
> Parse error: syntax error, unexpected
>
>
>
So, my questions are:
1. how can i make that code work?
2. is it possible to put the php code in cite.php file and output its values via a shortcode generated in functions.php? and how to do that?
Best regards
|
We've built shortcodes in the past using concatenating variables.
To paraphrase the link above, you should output your PHP as such.
```
$output = '<p>';
$output .= '<strong>' . $content . '</strong>';
$output .= '</p>';
return $output;
```
Note, see the `.=` variable concatenation.
|
202,502 |
<p>I have tried several options like setting <code>'container' => false</code> and registering the <strong>theme_location</strong> and searching on forums but I am unable to get rid of the "div" coming with the wp_nav_menu
in my page:</p>
<pre><code><?php get_nav_menu();?>
function get_nav_menu() {
$navMenuDefaults = array(
'theme_location' => 'header-nav',
'menu' => '',
'container' => false,
'container_class' => '',
'container_id' => '',
'menu_class' => '',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
return wp_nav_menu($navMenuDefaults);
}
</code></pre>
<p>and in functions.php:</p>
<pre><code>function register_top_nav() {
register_nav_menu('header-nav',__( 'Header Nav' ));
}
add_action( 'init', 'register_top_nav' );
</code></pre>
<p>I am not sure why I am getting the following output:</p>
<pre><code><div class="">
<ul>
<li class="page_item page-item-2">
<a href="url">Sample Page</a>
</li>
</ul>
</div>
</code></pre>
<p>How can I get something like following:</p>
<pre><code><ul class="abc">
<li>
<a href="#">dfdf</a>
</li>
</ul>
</code></pre>
<p>thanks.</p>
|
[
{
"answer_id": 202503,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 2,
"selected": false,
"text": "<p>FYI :<code>container => ''</code> is a string operation and it's default set by <code>div</code> you can't use <code>true or false like bool expression</code>.</p>\n\n<p>Just change the <code>container => 'ul'</code> then i hope you will get what you want to see.\nfor more details please read this : <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_nav_menu/</a></p>\n\n<p>Thanks\nMusa </p>\n"
},
{
"answer_id": 202532,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 0,
"selected": false,
"text": "<p>You can try with this scenario.</p>\n\n<p><strong>Step 1:</strong></p>\n\n<p>Put this code in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'theme_nav_setup' );\n\nif ( ! function_exists( 'theme_nav_setup' ) ){\n function theme_nav_setup() { \n register_nav_menu( 'header-nav_new', __( 'Main Menu', 'text-domain' ) );\n }\n}\n</code></pre>\n\n<p><strong>Step 2:</strong></p>\n\n<p>Then call this where you can see this menu output:</p>\n\n<pre><code>wp_nav_menu( array(\n 'menu' => 'header-nav_new',\n 'theme_location' => 'header-nav_new',\n 'depth' => 6,\n 'container' => 'ul',\n 'fallback_cb' => 'wp_page_menu',\n 'menu_class' => 'abc'\n )\n);\n</code></pre>\n"
},
{
"answer_id": 202673,
"author": "Muntasir Mahmud Aumio",
"author_id": 48345,
"author_profile": "https://wordpress.stackexchange.com/users/48345",
"pm_score": 0,
"selected": false,
"text": "<p>As you set \"container\" to false this should work unless there's a bug in anywhere either on the environment or a conflict with something else.</p>\n\n<p>In fact I've tested this in Twenty Fifteen and one of My themeforest Themes.</p>\n\n<p>Can you check if you have any internal cache that's not reflecting your changes right away?</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 232587,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<h2>Problem</h2>\n\n<p>You have not <a href=\"https://codex.wordpress.org/Appearance_Menus_SubPanel#Create_a_Menu\" rel=\"nofollow\">created a menu on the <code>Appearance > Menus</code> panel in the WordPress admin dashboard</a>.</p>\n\n<p>My reasoning is based on a bug which occurs under the following conditions:</p>\n\n<ul>\n<li>No navigation menus have been created</li>\n<li><code>wp_nav_menu()</code> was called with the default <code>'fallback_cb'</code> argument <code>'wp_page_menu'</code></li>\n<li><code>wp_nav_menu()</code> was called with a <code>'container'</code> argument intended to eliminate the container (anything which <a href=\"http://php.net/manual/en/function.empty.php\" rel=\"nofollow\">the <code>empty()</code> function</a> returns <code>true</code> for)</li>\n</ul>\n\n<hr>\n\n<h2>Solutions</h2>\n\n<p>Either of the following should remove the <code><div></code> container.</p>\n\n<ul>\n<li>Create a menu in the <code>Appearance > Menus</code> panel. The extraneous <code><div></code> should disappear even if you don't associate the new menu with your registered <code>'header-nav'</code> theme location.</li>\n<li><p>Change the <code>'fallback_cb'</code> argument to a custom function that returns some default markup - or even an empty string - i.e.</p>\n\n<pre><code>'fallback_cb' => function() { return ''; },\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h2>Explanation</h2>\n\n<p>In the event that the <code>wp_nav_menu()</code> function is unable to locate the indicated menu, it then tries two more things to produce menu markup:</p>\n\n<ol>\n<li>Display the first populated menu found.</li>\n<li>Display menu markup generated by the function indicated by the <code>'fallback_cb'</code> argument (by default, <a href=\"https://codex.wordpress.org/Function_Reference/wp_page_menu\" rel=\"nofollow\"><code>wp_page_menu()</code></a>).</li>\n</ol>\n\n<p>Your posted markup is for a <code>page</code> post-type with a post ID of <code>2</code> and the title \"Sample Page\", possibly indicating a new WordPress installation, for which it would be reasonable to assume no menus have been created. This indicated that your <code>wp_nav_menu()</code> call is likely falling back to <code>wp_page_menu()</code>, as the fallback function will create an impromptu menu from any number of pages in your installation.</p>\n\n<p>When the <code>'fallback_cb'</code> function is called, it is passed the same arguments that were given to <code>wp_nav_menu()</code> (merged with default arguments). Here the Codex documentation on the <code>wp_page_menu()</code> function is a little out of date, since as of WordPress 4.4.0 the function does actually accept and handle a <code>'container'</code> argument. So <code>wp_page_menu()</code> is getting called with the same <code>'container'</code> argument you handed to <code>wp_nav_menu()</code>, that being <code>''</code> (empty string literal) or <code>false</code>.</p>\n\n<p>The meat of the problem is a contradictory behavior that stems from <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/post-template.php#L1298\" rel=\"nofollow\">these lines</a> in <code>wp_page_menu()</code>:</p>\n\n<pre><code>// Fallback in case `wp_nav_menu()` was called without a container.\nif ( empty( $container ) ) {\n $container = 'div';\n}\n</code></pre>\n\n<p>So, since <code>empty()</code> evaluates both boolean <code>false</code> as well as <code>''</code> to <code>true</code>, this little fail-safe thinks you're crazy for not wanting a container and adds one back in \"for\" you.</p>\n"
},
{
"answer_id": 233645,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 1,
"selected": false,
"text": "<p>Yes you can use this code</p>\n\n<pre><code>$nav_menu = array(\n 'title_li' => '', \n 'container' => '',\n 'theme_location' => 'header-nav', \n 'menu_class' => '',\n 'menu_id' => '',\n); \n\nwp_nav_menu( $nav_menu );\n</code></pre>\n\n<p>The above code will display the menu in ul and li format without having any class and id to both ul and li tag</p>\n"
},
{
"answer_id": 240292,
"author": "Pakpoom Tiwakornkit",
"author_id": 76562,
"author_profile": "https://wordpress.stackexchange.com/users/76562",
"pm_score": 0,
"selected": false,
"text": "<p>From my own experience, if you haven't yet assign menu to the registered menu location, all argument settings prefixed with <code>container</code> won't work. you have to assign your created menu to the registered menu location before see the change.</p>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74229/"
] |
I have tried several options like setting `'container' => false` and registering the **theme\_location** and searching on forums but I am unable to get rid of the "div" coming with the wp\_nav\_menu
in my page:
```
<?php get_nav_menu();?>
function get_nav_menu() {
$navMenuDefaults = array(
'theme_location' => 'header-nav',
'menu' => '',
'container' => false,
'container_class' => '',
'container_id' => '',
'menu_class' => '',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
return wp_nav_menu($navMenuDefaults);
}
```
and in functions.php:
```
function register_top_nav() {
register_nav_menu('header-nav',__( 'Header Nav' ));
}
add_action( 'init', 'register_top_nav' );
```
I am not sure why I am getting the following output:
```
<div class="">
<ul>
<li class="page_item page-item-2">
<a href="url">Sample Page</a>
</li>
</ul>
</div>
```
How can I get something like following:
```
<ul class="abc">
<li>
<a href="#">dfdf</a>
</li>
</ul>
```
thanks.
|
FYI :`container => ''` is a string operation and it's default set by `div` you can't use `true or false like bool expression`.
Just change the `container => 'ul'` then i hope you will get what you want to see.
for more details please read this : <https://developer.wordpress.org/reference/functions/wp_nav_menu/>
Thanks
Musa
|
202,513 |
<p>I'm using the <a href="http://civicrm.org" rel="nofollow">CiviCRM</a> plugin for WordPress, and in the plugin's main file, <code>civicrm.php</code>, it calls <code>add_action()</code> to add a function to <code>wp_head()</code> in order to merge CiviCRM's header with my theme's header:</p>
<pre><code>add_action( 'wp_head', array( $this, 'wp_head' ) );
</code></pre>
<p>The actual function within civicrm.php is found below:</p>
<pre><code>public function wp_head() {
echo "calling wp_head"; //added by me to test if the code gets called
// CRM-11823 - If Civi bootstrapped, then merge its HTML header with the CMS's header
global $civicrm_root;
if ( empty( $civicrm_root ) ) {
return;
}
$region = CRM_Core_Region::instance('html-header', FALSE);
if ( $region ) {
echo '<!-- CiviCRM html header -->';
echo $region->render( '' );
}
}
</code></pre>
<p>I have confirmed that the code gets called when I switch to the twentyfifteen theme, but on my custom theme (which is based on an old version of <a href="http://roots.io" rel="nofollow">Roots</a>), this code does not get called. I have also confirmed that my custom theme is actually calling the main WordPress <code>wp_head()</code> function.</p>
<p>Any ideas on what could be going wrong in my custom theme that would cause this custom <code>wp_head</code> hook to not get called or otherwise error out in some way?</p>
|
[
{
"answer_id": 202535,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 1,
"selected": false,
"text": "<p>Can we think litter bit different way:</p>\n\n<pre><code>add_action('wp_head','new_wp_head');\nfunction new_wp_head() {\n echo \"calling wp_head\"; \n global $civicrm_root;\n if ( empty( $civicrm_root ) ) {\n return;\n }\n $region = CRM_Core_Region::instance('html-header', FALSE);\n if ( $region ) {\n echo '<!-- CiviCRM html header -->';\n echo $region->render( '' );\n }\n}\n</code></pre>\n\n<p>Make sure in which file you put this and it's hook with your theme or plugins.</p>\n"
},
{
"answer_id": 202545,
"author": "Nick Tiberi",
"author_id": 80285,
"author_profile": "https://wordpress.stackexchange.com/users/80285",
"pm_score": 1,
"selected": true,
"text": "<p>I figured out the issue:</p>\n\n<p>When CiviCRM was applying the template in <code>civicrm.basepage.php</code>, <code>$page_template</code> was coming back as <code>page.php</code>, but my base template was actually named <code>base.php</code>.</p>\n\n<p>I added the following code in my theme's initialization and it resolved the issue:</p>\n\n<pre><code>add_filter( 'civicrm_basepage_template', 'psca_civicrm_basepage_template' );\nfunction psca_civicrm_basepage_template( $template ) {\n return 'base.php';\n}\n</code></pre>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80285/"
] |
I'm using the [CiviCRM](http://civicrm.org) plugin for WordPress, and in the plugin's main file, `civicrm.php`, it calls `add_action()` to add a function to `wp_head()` in order to merge CiviCRM's header with my theme's header:
```
add_action( 'wp_head', array( $this, 'wp_head' ) );
```
The actual function within civicrm.php is found below:
```
public function wp_head() {
echo "calling wp_head"; //added by me to test if the code gets called
// CRM-11823 - If Civi bootstrapped, then merge its HTML header with the CMS's header
global $civicrm_root;
if ( empty( $civicrm_root ) ) {
return;
}
$region = CRM_Core_Region::instance('html-header', FALSE);
if ( $region ) {
echo '<!-- CiviCRM html header -->';
echo $region->render( '' );
}
}
```
I have confirmed that the code gets called when I switch to the twentyfifteen theme, but on my custom theme (which is based on an old version of [Roots](http://roots.io)), this code does not get called. I have also confirmed that my custom theme is actually calling the main WordPress `wp_head()` function.
Any ideas on what could be going wrong in my custom theme that would cause this custom `wp_head` hook to not get called or otherwise error out in some way?
|
I figured out the issue:
When CiviCRM was applying the template in `civicrm.basepage.php`, `$page_template` was coming back as `page.php`, but my base template was actually named `base.php`.
I added the following code in my theme's initialization and it resolved the issue:
```
add_filter( 'civicrm_basepage_template', 'psca_civicrm_basepage_template' );
function psca_civicrm_basepage_template( $template ) {
return 'base.php';
}
```
|
202,523 |
<p>I've got a shortcode that's got HTML in an $output field that's lovely. I just want to add one paragraph to it at the bottom that's conditional on this statement:</p>
<pre><code><?php if ( get_post_meta( get_the_ID(), 'campus', true ) ) : ?>
</code></pre>
<p>I can't quite figure out how to format a statement like that (if possible) into an existing $output field.</p>
<p>Here's what the $output looks like at present, I want to add this condition on line 8 and basically have another paragraph tag with some content there that shows there only if the statement is true:</p>
<pre><code>'<div class="w-blog-entry" style="padding:0;">
<div class="w-blog-entry-h">
<div class="l-subsection color_dark" style="background-image: url('.$the_thumbnail.'); background-position: center center; padding-top:0; padding-bottom:0; background-attachment: inherit;">
<div class="l-subsection-h">
<div class="l-subsection-hh g-html i-cf" style="font-family:Century Gothic; text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);">
<a class="w-blog-entry-link" href="'.get_permalink(get_the_ID()).'"><h2 class="w-blog-entry-title" style="line-height:1em; margin-left:0; padding-left:4px; font-size:20px;"><span class="w-blog-entry-title-h" style="color:#fff;">'.get_post_meta( get_the_ID(), 'destination', true ).'<br><span style="font-size:0.6em; color:#f2f2f2;">'.get_post_meta( get_the_ID(), 'depart', true ).' <span style="text-transform: lowercase; font-size:0.8em;">to</span> '.get_post_meta( get_the_ID(), 'return', true ).'</span></span></h2></a>
<p style="line-height:1.2em; padding-left:4px; font-size:0.9em;">'.get_post_meta( get_the_ID(), 'projectdesc', true ).'</p>
</div>
</div>
</div>
</div>';
}
$output .= '</div>
</div>
</div>'
</code></pre>
<p>Is this possible, or do I have to make a whole other condition to the shortcode with two outputs?</p>
<p>Let me know if you need more context from the shortcode, I just didn't want to waste too much space if my original goal is possible.</p>
|
[
{
"answer_id": 202544,
"author": "Peter Rigby",
"author_id": 70894,
"author_profile": "https://wordpress.stackexchange.com/users/70894",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand you right you just want to use a '?' type of if statement:</p>\n\n<pre><code>$output = '<div class=\"w-blog-entry\" style=\"padding:0;\">\n <div class=\"w-blog-entry-h\">\n <div class=\"l-subsection color_dark\" style=\"background-image: url('.$the_thumbnail.'); background-position: center center; padding-top:0; padding-bottom:0; background-attachment: inherit;\">\n <div class=\"l-subsection-h\">\n <div class=\"l-subsection-hh g-html i-cf\" style=\"font-family:Century Gothic; text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\">\n <a class=\"w-blog-entry-link\" href=\"'.get_permalink(get_the_ID()).'\"><h2 class=\"w-blog-entry-title\" style=\"line-height:1em; margin-left:0; padding-left:4px; font-size:20px;\"><span class=\"w-blog-entry-title-h\" style=\"color:#fff;\">'.get_post_meta( get_the_ID(), 'destination', true ).'<br><span style=\"font-size:0.6em; color:#f2f2f2;\">'.get_post_meta( get_the_ID(), 'depart', true ).' <span style=\"text-transform: lowercase; font-size:0.8em;\">to</span> '.get_post_meta( get_the_ID(), 'return', true ).'</span></span></h2></a>\n <p style=\"line-height:1.2em; padding-left:4px; font-size:0.9em;\">'.get_post_meta( get_the_ID(), 'projectdesc', true ).'</p>';\n$output .= get_post_meta( get_the_ID(), 'campus', true ) ? '<p>True so do this paragraph</p>' : '<p>false, so do this instead</p>';\n$output.=' </div>\n </div>\n </div>\n\n </div>';\n</code></pre>\n\n<p>A standard if else would have worked OK too so I'm not sure where the confusion was.</p>\n\n<p>Another way is to use a php output buffer which would work like this:</p>\n\n<pre><code>ob_start();\n?>\n<div class=\"w-blog-entry\" style=\"padding:0;\"> etc etc\n<?php if(get_post_meta( get_the_ID(), 'campus', true )) {?>\n<p>True paragraph</p>\n<?php }else{ ?>\n<p>false paragraph</p>\n<?php } ?>\n</code></pre>\n\n<p>And then when you've finished with all your output you put it in your $output variable like this:</p>\n\n<pre><code>$output = ob_get_clean();\n</code></pre>\n\n<p>When you start an output buffer it basically means that any HTML you put outside of the PHP tags goes into the buffer rather than being output to the browser. I prefer this sometimes when there's a lot of different conditions and logic in the output.</p>\n\n<p><a href=\"http://php.net/manual/en/function.ob-start.php\" rel=\"nofollow\">ob_start</a>, <a href=\"http://php.net/manual/en/function.ob-get-clean.php\" rel=\"nofollow\">ob_get_clean</a></p>\n"
},
{
"answer_id": 202555,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 0,
"selected": false,
"text": "<p><code>$output = 'Hello World !';</code> mean you just assignment a value in $output variable.but when you use like <br>\n<code>$a = 1;\n$output = 'Hello';\nif($a == 1){\n $output .= 'World';\n}else{\n $output .= 'Universe';\n}\n$output .= '!';\n</code>if you print this $output then output will be same like <code>Hello World !</code> because of concatenation.<br></p>\n\n<p>so if you are not clear about <code>(your_statement) ? 'True' : 'False'</code> like \n<code>get_post_meta( get_the_ID(), 'campus', true ) ? '<p>True so do this paragraph</p>' : '<p>false, so do this instead</p>';</code> <br>\nyou can write this instead this like <br>\n<code>\nif(get_post_meta( get_the_ID(), 'campus', true )){\n $output .= '<p>True so do this paragraph</p>';\n}else{\n $output .= <p>false, so do this instead</p>';\n}</code></p>\n\n<p>Thanks\nMusa</p>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79967/"
] |
I've got a shortcode that's got HTML in an $output field that's lovely. I just want to add one paragraph to it at the bottom that's conditional on this statement:
```
<?php if ( get_post_meta( get_the_ID(), 'campus', true ) ) : ?>
```
I can't quite figure out how to format a statement like that (if possible) into an existing $output field.
Here's what the $output looks like at present, I want to add this condition on line 8 and basically have another paragraph tag with some content there that shows there only if the statement is true:
```
'<div class="w-blog-entry" style="padding:0;">
<div class="w-blog-entry-h">
<div class="l-subsection color_dark" style="background-image: url('.$the_thumbnail.'); background-position: center center; padding-top:0; padding-bottom:0; background-attachment: inherit;">
<div class="l-subsection-h">
<div class="l-subsection-hh g-html i-cf" style="font-family:Century Gothic; text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);">
<a class="w-blog-entry-link" href="'.get_permalink(get_the_ID()).'"><h2 class="w-blog-entry-title" style="line-height:1em; margin-left:0; padding-left:4px; font-size:20px;"><span class="w-blog-entry-title-h" style="color:#fff;">'.get_post_meta( get_the_ID(), 'destination', true ).'<br><span style="font-size:0.6em; color:#f2f2f2;">'.get_post_meta( get_the_ID(), 'depart', true ).' <span style="text-transform: lowercase; font-size:0.8em;">to</span> '.get_post_meta( get_the_ID(), 'return', true ).'</span></span></h2></a>
<p style="line-height:1.2em; padding-left:4px; font-size:0.9em;">'.get_post_meta( get_the_ID(), 'projectdesc', true ).'</p>
</div>
</div>
</div>
</div>';
}
$output .= '</div>
</div>
</div>'
```
Is this possible, or do I have to make a whole other condition to the shortcode with two outputs?
Let me know if you need more context from the shortcode, I just didn't want to waste too much space if my original goal is possible.
|
If I understand you right you just want to use a '?' type of if statement:
```
$output = '<div class="w-blog-entry" style="padding:0;">
<div class="w-blog-entry-h">
<div class="l-subsection color_dark" style="background-image: url('.$the_thumbnail.'); background-position: center center; padding-top:0; padding-bottom:0; background-attachment: inherit;">
<div class="l-subsection-h">
<div class="l-subsection-hh g-html i-cf" style="font-family:Century Gothic; text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);">
<a class="w-blog-entry-link" href="'.get_permalink(get_the_ID()).'"><h2 class="w-blog-entry-title" style="line-height:1em; margin-left:0; padding-left:4px; font-size:20px;"><span class="w-blog-entry-title-h" style="color:#fff;">'.get_post_meta( get_the_ID(), 'destination', true ).'<br><span style="font-size:0.6em; color:#f2f2f2;">'.get_post_meta( get_the_ID(), 'depart', true ).' <span style="text-transform: lowercase; font-size:0.8em;">to</span> '.get_post_meta( get_the_ID(), 'return', true ).'</span></span></h2></a>
<p style="line-height:1.2em; padding-left:4px; font-size:0.9em;">'.get_post_meta( get_the_ID(), 'projectdesc', true ).'</p>';
$output .= get_post_meta( get_the_ID(), 'campus', true ) ? '<p>True so do this paragraph</p>' : '<p>false, so do this instead</p>';
$output.=' </div>
</div>
</div>
</div>';
```
A standard if else would have worked OK too so I'm not sure where the confusion was.
Another way is to use a php output buffer which would work like this:
```
ob_start();
?>
<div class="w-blog-entry" style="padding:0;"> etc etc
<?php if(get_post_meta( get_the_ID(), 'campus', true )) {?>
<p>True paragraph</p>
<?php }else{ ?>
<p>false paragraph</p>
<?php } ?>
```
And then when you've finished with all your output you put it in your $output variable like this:
```
$output = ob_get_clean();
```
When you start an output buffer it basically means that any HTML you put outside of the PHP tags goes into the buffer rather than being output to the browser. I prefer this sometimes when there's a lot of different conditions and logic in the output.
[ob\_start](http://php.net/manual/en/function.ob-start.php), [ob\_get\_clean](http://php.net/manual/en/function.ob-get-clean.php)
|
202,526 |
<p>This thing makes my coding difficult.
Wordpress codex reasons the use of esc_url by talking vaguely about security.
But is it really worth the trouble?</p>
<p>For example, what's the important, practical security benefit by using</p>
<pre><code><?php echo esc_url( home_url( '/' ) ); ?>
</code></pre>
<p>instead of</p>
<pre><code><?php echo home_url() ?>
</code></pre>
<p>PS: I am not talking about theme development, but about a specific site.</p>
|
[
{
"answer_id": 202527,
"author": "matthew",
"author_id": 52429,
"author_profile": "https://wordpress.stackexchange.com/users/52429",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"nofollow\">esc_url</a> is used to produce a valid HTML (not to sanitize input). You should use this anytime you are not 100% sure that what you want to output is a valid HTML for that context.</p>\n"
},
{
"answer_id": 202530,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 5,
"selected": true,
"text": "<p>If you check the documentation on <a href=\"https://codex.wordpress.org/Data_Validation#URLs\">Data Validation</a> it has following to say about the function:</p>\n\n<blockquote>\n <p>Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols [...], eliminates invalid characters, and removes dangerous characters.</p>\n</blockquote>\n\n<p>There you have it — practical security benefit. Valid protocol, no murky characters.</p>\n\n<p>The answer about necessity is firmly <strong>yes</strong>. Escaping output is the most basic security practice. </p>\n"
},
{
"answer_id": 202533,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 2,
"selected": false,
"text": "<p>Another things must be keep in your head about\n<code>esc_url()</code> is for something like <code><a href=\"SANITIZE_THIS_URL\">your_text</a></code>.if you’re going to use the URL in your HTML output, like a href attribute for a link, or a src attribute for an image element, you should use <code>esc_url()</code>.</p>\n\n<p><code>esc_url_raw()</code>is for other cases where you want a clean URL, but you don’t want HTML entities to be encoded. So any non-HTML usage (DB, redirect) would use this.</p>\n\n<p>The <code>esc_url_raw()</code> function will do pretty much the same as <code>esc_url()</code>, but it will not decode entities, meaning it will not replace & with &#038 and so on. As Mark pointed out, it’s safe to use <code>esc_url_raw()</code> in database queries, redirects and HTTP functions, such as `wp_remote_get()'\nfor more info about <a href=\"http://codex.wordpress.org/Function_Reference/esc_url_raw\" rel=\"nofollow\">esc_url_raw()</a></p>\n"
},
{
"answer_id": 202554,
"author": "Tomer W",
"author_id": 80302,
"author_profile": "https://wordpress.stackexchange.com/users/80302",
"pm_score": 2,
"selected": false,
"text": "<p>well, all user input should be sanitized...\nIf the url you inject is not user input (e.g. site setting by someone you fully trust, hardcoded values) then you may relief yourself from esc-url.</p>\n\n<p>but if I could inject that url to your site, i could easily inject js code, or redirection code... or even server side code in some situations.</p>\n\n<p>this can lead to session hijacking and your users accounts being stolen and other bad options.</p>\n\n<h2>Edit:</h2>\n\n<p>In your example <code>esc_url( home_url( '/' ) );</code><br>\nit operated on a semi-hardcoded value! therefore <code>esc_url</code> can be eliminated.<br>\nThat said I still don't see why bother distinctions between when there is a threat and when there is not and generally would suggest to keep esc_url() for every value.</p>\n"
}
] |
2015/09/12
|
[
"https://wordpress.stackexchange.com/questions/202526",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
This thing makes my coding difficult.
Wordpress codex reasons the use of esc\_url by talking vaguely about security.
But is it really worth the trouble?
For example, what's the important, practical security benefit by using
```
<?php echo esc_url( home_url( '/' ) ); ?>
```
instead of
```
<?php echo home_url() ?>
```
PS: I am not talking about theme development, but about a specific site.
|
If you check the documentation on [Data Validation](https://codex.wordpress.org/Data_Validation#URLs) it has following to say about the function:
>
> Always use esc\_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols [...], eliminates invalid characters, and removes dangerous characters.
>
>
>
There you have it — practical security benefit. Valid protocol, no murky characters.
The answer about necessity is firmly **yes**. Escaping output is the most basic security practice.
|
202,550 |
<p>I have been searching for several hours to find a way to embed the "Add New Post" inside a page in the front end. I read <a href="https://wordpress.stackexchange.com/questions/128288/how-can-i-place-the-add-new-post-contents-on-a-custom-page">this post</a> but sadly no answer to it. </p>
<p>I have embedded the login form in another page called (example.com/user-login) and What I want is to have a page (example.com/add-post) which allows the person who logged in to publish a post in a page that is within the WordPress theme. </p>
<p>The same way as default method of publishing a post (example.com/wp-admin/post-new.php) but without going to the wordpress dashboard. </p>
<p>I have found several plugins that allow <strong>guest posts</strong>, but I want to <strong>person who logged in</strong>, be able to post. </p>
|
[
{
"answer_id": 202551,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": -1,
"selected": false,
"text": "<p>You have never read the WP documentation?</p>\n\n<p>Create any template and form and when submitting the form it could be</p>\n\n<p>Example:</p>\n\n<pre><code>$args = array('post_type'=>'post', 'post_title'=>'your title', 'post_status'=>'publish', 'post_content'=>'post content');\n\nwp_insert_post ($args);\n</code></pre>\n\n<p>This will allow any post page or custom post type to insert the post</p>\n"
},
{
"answer_id": 214743,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<p>This is pretty simple. So simple you need to make sure your guests don't insert bad code into you DB. So read up on <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow\">Data Validation</a> and <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow\">Validating Sanitizing and Escaping User Data</a> before you add anything to your site from a front-end form.</p>\n\n<ol>\n<li>Create a new page at <code>/new-post</code></li>\n<li>Create a page template to target that page</li>\n<li>Setup AJAX actions</li>\n<li>Render your form inside the custom page template.</li>\n<li>Use jQuery to submit the form details to AJAX</li>\n<li>AJAX action will validate the data</li>\n<li>If good, the new post will be created</li>\n<li>AJAX will output a success or fail response</li>\n<li>jQuery on the front-end form will inform the user of success or failure.</li>\n</ol>\n\n<p>First, create a page called <code>new-post</code> that will hold your form. Then create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page\" rel=\"nofollow\">page template</a> to target that page using the file structure <code>page-{slug}.php</code>.</p>\n\n<pre><code>page-new-post.php\n</code></pre>\n\n<p>On that page you can check to see if <a href=\"https://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow\">is_user_logged_in</a> and if they have the ability to create posts using <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow\">current_user_can</a>. If not, you can always <a href=\"https://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\">wp_redirect</a> elsewhere or just <a href=\"https://codex.wordpress.org/Function_Reference/wp_die\" rel=\"nofollow\">wp_die</a>.</p>\n\n<p>You'll need to do all this with <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">AJAX</a> so create a front-end form that when clicked; submits data to WP, validates, and creates a new post. </p>\n\n<p>Take note of <code>_nopriv</code> which you don't want to use in your case because someone will SPAM your site to a crawl.</p>\n\n<pre><code>// AJAX for logged in users\n\nadd_action( 'wp_ajax_create_new_post', 'ajax_create_new_post_action' );\n\n// AJAX for non-logged in users\n\nadd_action( 'wp_ajax_nopriv_create_new_post', 'ajax_nopriv_create_new_post_action' );\n</code></pre>\n\n<p>Once you've collected the data and sanitized it in your <code>ajax_create_new_post_action</code> then you'll need to create a new post with <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow\">wp_insert_post</a>.</p>\n\n<hr>\n\n<p>Since there are quite a few steps involved I recommend generating most of this automatically using <a href=\"http://chrisplaneta.com/generators/wpsecureforms/\" rel=\"nofollow\">WP Secure Forms</a> and filling in the gaps after. Here is an example of an AJAX email submission form to give you a pretty good overview of the AJAX parts -- including sanitization.</p>\n\n<h2>Template for <a href=\"http://chrisplaneta.com/generators/wpsecureforms/\" rel=\"nofollow\">WP Secure Forms</a></h2>\n\n<pre><code>Title {30 characters limit}\n> * 30\n| Your Title\n! Field specific error message\n\n\nTextarea{150 characters limit}\n> 150\n| Content\n|\n|\n! Field specific error message\n\n\nThis label is invisible\n> H\n</code></pre>\n\n<h2>Form</h2>\n\n<p>This script goes into the PHP file of your theme.</p>\n\n<pre><code><p id=\"wpse_form_message_wrap\" class=\"secureforms-message-wrap\"></p>\n\n<form id=\"wpse_form\" method=\"post\">\n\n <div id=\"wpse_form_10000-wrapper\">\n <label for=\"wpse_form_10000\">* Title <span>30 characters limit</span></label>\n <input type=\"text\" name=\"wpse_form_10000\" id=\"wpse_form_10000\" value=\"\" placeholder=\"Your Title\" required=\"required\" maxlength=\"30\" />\n <p class=\"secureforms-error-msg\">Field specific error message</p>\n </div>\n\n <div id=\"wpse_form_20000-wrapper\">\n <label for=\"wpse_form_20000\">Textarea{150 characters limit}</label>\n <textarea rows=\"3\" name=\"wpse_form_20000\" id=\"wpse_form_20000\" value=\"\" maxlength=\"150\" ></textarea>\n <p class=\"secureforms-error-msg\">Field specific error message</p>\n </div>\n\n <div id=\"wpse_form_30000-wrapper\" class=\"secureforms-hidden-wrapper\">\n <input id=\"wpse_form_30000\" name=\"wpse_form_30000\" type=\"hidden\">\n </div>\n\n <div id=\"wpse_form_footer\">\n <input type=\"hidden\" id=\"check_wpse_form\" name=\"check_wpse_form\" value=\"\" />\n <input type=\"hidden\" name=\"action\" value=\"wpse_form\" />\n <?php echo wp_nonce_field('wpse_form', '_nonce_eklwu', true, false); ?>\n <input type=\"submit\" name=\"wpse_form_submit_btn\" id=\"wpse_form_submit_btn\" value=\"Submit\" />\n </div>\n\n</form>\n</code></pre>\n\n<h2>Functions.php</h2>\n\n<p>This one goes into your functions.php</p>\n\n<pre><code>// WP SECURE FORMS - EMAIL VALIDATION & SENDING \n\nrequire_once( 'ajax/wpse_form.php' );\n\n// WP SECURE FORMS - ENQUEUE EMAIL JS \n\nfunction enqueue_ajax_wpse_form() {\n\n if (!is_admin()) {\n wp_enqueue_script( 'ajax_wpse_form', get_template_directory_uri().'/ajax/wpse_form.js', array('jquery'), '', true );\n wp_localize_script( 'ajax_wpse_form', 'ajax_wpse_form', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n }\n}\n\nadd_action( 'wp_enqueue_scripts', 'enqueue_ajax_wpse_form', 999 );\n</code></pre>\n\n<h2>Validation</h2>\n\n<p>In your theme folder create an \"ajax\" folder with the file named wpse_form.php. Paste into it the code below.</p>\n\n<pre><code><?php \n\nfunction ajax_wpse_form_action() { \n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\"){ \n\n $return_message = '';\n $status = 'success';\n $fields_with_errors = array(); \n\n // validate nonce\n if(!wp_verify_nonce($_POST['_nonce_eklwu'], $_POST['action'])){\n $status = 'error';\n }\n\n // validate hidden field\n if(!empty(trim($_POST['check_wpse_form']))){\n $status = 'error';\n }\n\n if ($status == 'error') {\n $return_message = 'Data verification error. Check marked fields.';\n } else {\n\n $wpse_form_10000 = strip_tags(trim(stripslashes($_POST['wpse_form_10000'])));\n\n if(!empty($wpse_form_10000)){\n if(strlen($wpse_form_10000) > 30){\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_10000';\n }\n } else {\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_10000';\n }\n\n $wpse_form_20000 = strip_tags(trim(stripslashes($_POST['wpse_form_20000'])));\n\n if(!empty($wpse_form_20000)){\n if(strlen($wpse_form_20000) > 150){\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_20000';\n }\n }\n\n $wpse_form_30000 = strip_tags(trim(stripslashes($_POST['wpse_form_30000'])));\n if ($status == 'error') {\n $return_message = 'Data verification error. Check marked fields.';\n } else {\n\n // message\n $to = '[email protected]';\n $header = 'From: '. get_bloginfo('name') . ' <[email protected]>'.PHP_EOL;\n $subject = 'Test Email Subject';\n $formMessage = '';\n\n $formMessage .= 'Title {30 characters limit}' . \"\\n\";\n $formMessage .= $wpse_form_10000 . \"\\n\\n\";\n $formMessage .= 'Textarea{150 characters limit}' . \"\\n\";\n $formMessage .= $wpse_form_20000 . \"\\n\\n\";\n $formMessage .= 'This label is invisible' . \"\\n\";\n $formMessage .= $wpse_form_30000 . \"\\n\\n\";\n if ( wp_mail($to, $subject, $formMessage, $header) ) {\n $return_message = 'Thank you for contacting us. We will get in touch as soon as possible.';\n } else {\n $status = 'error';\n $return_message = 'There was an error sending the message. Please try again.';\n }\n }\n }\n\n $resp = array(\n 'status' => $status,\n 'return_message' => $return_message,\n 'fields_with_errors' => $fields_with_errors,\n );\n\n header( \"Content-Type: application/json\" );\n echo json_encode($resp);\n die();\n\n} else {\n http_response_code(403);\n}\n}\n\nadd_action( 'wp_ajax_wpse_form', 'ajax_wpse_form_action' );\nadd_action( 'wp_ajax_nopriv_wpse_form', 'ajax_wpse_form_action' );\n</code></pre>\n\n<h2>AJAX</h2>\n\n<p>In your theme folder create an \"ajax\" folder with the file named wpse_form.js. Paste into it this code.</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n var wpse_form_btn = $('#wpse_form_submit_btn');\n\n function init_wpse_form(){\n\n /* VARS */\n\n var form = $('#wpse_form'),\n type = form.attr('method'),\n requiredFields = ['wpse_form_10000 | textline'];\n\n /* FUNCTIONS */\n\n function showErrors(fieldsWithErrors){\n\n form.find('.hasError').removeClass('hasError').end().find('.secureforms-error-msg.active').removeClass('active');\n\n for(var i=0; i< fieldsWithErrors.length; i++){\n if(fieldsWithErrors[i].length > 0){\n $('#' + fieldsWithErrors[i]).addClass('hasError').next().addClass('active');\n }\n }\n }\n\n /* TRIGGER */\n\n wpse_form_btn.on('click', function(e){\n\n e.preventDefault();\n e.stopPropagation();\n\n if($('#check_wpse_form').val()){\n return false;\n } else {\n\n var emptyErrors = [];\n\n for(var i = 0; i<requiredFields.length; i++){\n\n var fieldData = requiredFields[i].split(' | '),\n field = $('#' + fieldData[0]),\n fieldType = fieldData[1];\n\n if(fieldType == 'select'){\n var selected = field.find(':selected');\n if(selected.length > 0){\n if(selected.val() == 'wpse_form_select_null'){\n emptyErrors.push(fieldData[0]);\n }\n } else {\n emptyErrors.push(fieldData[0]);\n }\n } else if(fieldType == 'radio' || fieldType == 'checkbox'){\n if(field.find('input:checked').length <= 0){\n emptyErrors.push(fieldData[0]);\n }\n } else {\n if(!field.val()){\n emptyErrors.push(fieldData[0]);\n }\n }\n }\n\n if(emptyErrors.length > 0){\n showErrors(emptyErrors);\n $('#wpse_form_message_wrap').removeClass('success').addClass('error').text('Please fill all the required fields');\n return false;\n } else {\n\n var data = form.serialize();\n $.ajax({\n type: type,\n url: ajax_wpse_form.ajax_url,\n data: data,\n dataType: 'json',\n success: function(response) {\n\n if (response.status == 'success') {\n $('#wpse_form_message_wrap')\n .removeClass('error')\n .addClass('success')\n .text(response.return_message);\n\n showErrors([]);\n\n } else {\n $('#wpse_form_message_wrap')\n .removeClass('success')\n .addClass('error')\n .text(response.return_message);\n\n showErrors(response.fields_with_errors);\n }\n },\n error: function(xhr,err){\n console.log(\"readyState: \"+xhr.readyState+\"\\\nstatus: \"+xhr.status);\n console.log(\"responseText: \"+xhr.responseText);\n }\n })\n }\n }\n });\n };\n\n if(wpse_form_btn.length > 0){\n init_wpse_form();\n }\n\n});\n</code></pre>\n\n<h2>JS</h2>\n\n<p>Paste this code into your theme's main js file.</p>\n\n<pre><code>$('body').on('click', 'input[type=radio]', function(){\n\n var wrapper = $(this).parent(),\n triggers = wrapper.find('.isTrigger');\n\n if(triggers.length > 0){\n triggers.each(function(){\n if($(this).is(':checked')){\n $('.' + $(this).attr('data-toggle')).slideDown(200);\n } else {\n $('.' + $(this).attr('data-toggle')).slideUp(200);\n }\n })\n }\n\n})\n\n$('body').on('click', 'input[type=checkbox]', function(){\n\n var that = $(this),\n wrapper = that.parent(),\n limit = wrapper.attr('data-limit'),\n chosen = wrapper.find('input:checked').length;\n\n // disabling / enabling choices\n if(that.is(':checked')){\n if(chosen + 1 > limit){\n wrapper.find('input').not(':checked').prop('disabled', true);\n }\n } else {\n wrapper.find('input').prop('disabled', false);\n }\n\n // conditional showing / hiding fields\n if(that.hasClass('isTrigger')){\n\n var targetClass = that.attr('data-toggle');\n\n if(that.is(':checked')){\n $('.' + targetClass).slideDown(200);\n } else {\n $('.' + targetClass).slideUp(200);\n }\n }\n})\n\n$('body').on('change', 'select', function(){\n\n var that = $(this),\n wrapper = that.parent(),\n triggers = wrapper.find('.isTrigger'),\n options = wrapper.find('option');\n\n if(triggers.length > 0){\n options.each(function(){\n if($(this).is(':selected')){\n if($(this).hasClass('isTrigger')){\n $('.' + $(this).attr('data-toggle')).slideDown(200);\n }\n } else {\n if($(this).hasClass('isTrigger')){\n $('.' + $(this).attr('data-toggle')).slideUp(200);\n }\n }\n })\n }\n})\n</code></pre>\n\n<h2>CSS</h2>\n\n<p>Paste the code below into your theme's main css file.</p>\n\n<pre><code>form>div, form>p{\n margin-top: 0;\n margin-bottom: 1em;\n}\nform fieldset {\n margin: 0;\n border: none;\n padding: 0;\n}\nform label, form legend{\n display: block;\n margin-bottom: .25em;\n}\nform label span, form legend span{\n font-size: .8em;\n font-style: italic;\n}\nform label span::before, form legend span::before{\n content: '';\n display: block;\n}\ninput[type=\"checkbox\"]+label, input[type=\"radio\"]+label, input[type=\"number\"]+label{\n display: inline-block;\n}\nform .showOnTrigger{\n display: none;\n}\n.secureforms-error-msg{\n display: none;\n color: red;\n}\n.secureforms-error-msg.active{\n display: block;\n}\n.secureforms-hidden-wrapper{\n display: none;\n}\n.secureforms-message-wrap.error{\n border: 2px solid red;\n}\n.secureforms-message-wrap.success{\n border: 2px solid green;\n}\n</code></pre>\n"
}
] |
2015/09/13
|
[
"https://wordpress.stackexchange.com/questions/202550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80301/"
] |
I have been searching for several hours to find a way to embed the "Add New Post" inside a page in the front end. I read [this post](https://wordpress.stackexchange.com/questions/128288/how-can-i-place-the-add-new-post-contents-on-a-custom-page) but sadly no answer to it.
I have embedded the login form in another page called (example.com/user-login) and What I want is to have a page (example.com/add-post) which allows the person who logged in to publish a post in a page that is within the WordPress theme.
The same way as default method of publishing a post (example.com/wp-admin/post-new.php) but without going to the wordpress dashboard.
I have found several plugins that allow **guest posts**, but I want to **person who logged in**, be able to post.
|
This is pretty simple. So simple you need to make sure your guests don't insert bad code into you DB. So read up on [Data Validation](https://codex.wordpress.org/Data_Validation) and [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data) before you add anything to your site from a front-end form.
1. Create a new page at `/new-post`
2. Create a page template to target that page
3. Setup AJAX actions
4. Render your form inside the custom page template.
5. Use jQuery to submit the form details to AJAX
6. AJAX action will validate the data
7. If good, the new post will be created
8. AJAX will output a success or fail response
9. jQuery on the front-end form will inform the user of success or failure.
First, create a page called `new-post` that will hold your form. Then create a [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page) to target that page using the file structure `page-{slug}.php`.
```
page-new-post.php
```
On that page you can check to see if [is\_user\_logged\_in](https://codex.wordpress.org/Function_Reference/is_user_logged_in) and if they have the ability to create posts using [current\_user\_can](https://codex.wordpress.org/Function_Reference/current_user_can). If not, you can always [wp\_redirect](https://codex.wordpress.org/Function_Reference/wp_redirect) elsewhere or just [wp\_die](https://codex.wordpress.org/Function_Reference/wp_die).
You'll need to do all this with [AJAX](https://codex.wordpress.org/AJAX_in_Plugins) so create a front-end form that when clicked; submits data to WP, validates, and creates a new post.
Take note of `_nopriv` which you don't want to use in your case because someone will SPAM your site to a crawl.
```
// AJAX for logged in users
add_action( 'wp_ajax_create_new_post', 'ajax_create_new_post_action' );
// AJAX for non-logged in users
add_action( 'wp_ajax_nopriv_create_new_post', 'ajax_nopriv_create_new_post_action' );
```
Once you've collected the data and sanitized it in your `ajax_create_new_post_action` then you'll need to create a new post with [wp\_insert\_post](https://codex.wordpress.org/Function_Reference/wp_insert_post).
---
Since there are quite a few steps involved I recommend generating most of this automatically using [WP Secure Forms](http://chrisplaneta.com/generators/wpsecureforms/) and filling in the gaps after. Here is an example of an AJAX email submission form to give you a pretty good overview of the AJAX parts -- including sanitization.
Template for [WP Secure Forms](http://chrisplaneta.com/generators/wpsecureforms/)
---------------------------------------------------------------------------------
```
Title {30 characters limit}
> * 30
| Your Title
! Field specific error message
Textarea{150 characters limit}
> 150
| Content
|
|
! Field specific error message
This label is invisible
> H
```
Form
----
This script goes into the PHP file of your theme.
```
<p id="wpse_form_message_wrap" class="secureforms-message-wrap"></p>
<form id="wpse_form" method="post">
<div id="wpse_form_10000-wrapper">
<label for="wpse_form_10000">* Title <span>30 characters limit</span></label>
<input type="text" name="wpse_form_10000" id="wpse_form_10000" value="" placeholder="Your Title" required="required" maxlength="30" />
<p class="secureforms-error-msg">Field specific error message</p>
</div>
<div id="wpse_form_20000-wrapper">
<label for="wpse_form_20000">Textarea{150 characters limit}</label>
<textarea rows="3" name="wpse_form_20000" id="wpse_form_20000" value="" maxlength="150" ></textarea>
<p class="secureforms-error-msg">Field specific error message</p>
</div>
<div id="wpse_form_30000-wrapper" class="secureforms-hidden-wrapper">
<input id="wpse_form_30000" name="wpse_form_30000" type="hidden">
</div>
<div id="wpse_form_footer">
<input type="hidden" id="check_wpse_form" name="check_wpse_form" value="" />
<input type="hidden" name="action" value="wpse_form" />
<?php echo wp_nonce_field('wpse_form', '_nonce_eklwu', true, false); ?>
<input type="submit" name="wpse_form_submit_btn" id="wpse_form_submit_btn" value="Submit" />
</div>
</form>
```
Functions.php
-------------
This one goes into your functions.php
```
// WP SECURE FORMS - EMAIL VALIDATION & SENDING
require_once( 'ajax/wpse_form.php' );
// WP SECURE FORMS - ENQUEUE EMAIL JS
function enqueue_ajax_wpse_form() {
if (!is_admin()) {
wp_enqueue_script( 'ajax_wpse_form', get_template_directory_uri().'/ajax/wpse_form.js', array('jquery'), '', true );
wp_localize_script( 'ajax_wpse_form', 'ajax_wpse_form', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_wpse_form', 999 );
```
Validation
----------
In your theme folder create an "ajax" folder with the file named wpse\_form.php. Paste into it the code below.
```
<?php
function ajax_wpse_form_action() {
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$return_message = '';
$status = 'success';
$fields_with_errors = array();
// validate nonce
if(!wp_verify_nonce($_POST['_nonce_eklwu'], $_POST['action'])){
$status = 'error';
}
// validate hidden field
if(!empty(trim($_POST['check_wpse_form']))){
$status = 'error';
}
if ($status == 'error') {
$return_message = 'Data verification error. Check marked fields.';
} else {
$wpse_form_10000 = strip_tags(trim(stripslashes($_POST['wpse_form_10000'])));
if(!empty($wpse_form_10000)){
if(strlen($wpse_form_10000) > 30){
$status = 'error';
$fields_with_errors[] = 'wpse_form_10000';
}
} else {
$status = 'error';
$fields_with_errors[] = 'wpse_form_10000';
}
$wpse_form_20000 = strip_tags(trim(stripslashes($_POST['wpse_form_20000'])));
if(!empty($wpse_form_20000)){
if(strlen($wpse_form_20000) > 150){
$status = 'error';
$fields_with_errors[] = 'wpse_form_20000';
}
}
$wpse_form_30000 = strip_tags(trim(stripslashes($_POST['wpse_form_30000'])));
if ($status == 'error') {
$return_message = 'Data verification error. Check marked fields.';
} else {
// message
$to = '[email protected]';
$header = 'From: '. get_bloginfo('name') . ' <[email protected]>'.PHP_EOL;
$subject = 'Test Email Subject';
$formMessage = '';
$formMessage .= 'Title {30 characters limit}' . "\n";
$formMessage .= $wpse_form_10000 . "\n\n";
$formMessage .= 'Textarea{150 characters limit}' . "\n";
$formMessage .= $wpse_form_20000 . "\n\n";
$formMessage .= 'This label is invisible' . "\n";
$formMessage .= $wpse_form_30000 . "\n\n";
if ( wp_mail($to, $subject, $formMessage, $header) ) {
$return_message = 'Thank you for contacting us. We will get in touch as soon as possible.';
} else {
$status = 'error';
$return_message = 'There was an error sending the message. Please try again.';
}
}
}
$resp = array(
'status' => $status,
'return_message' => $return_message,
'fields_with_errors' => $fields_with_errors,
);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
} else {
http_response_code(403);
}
}
add_action( 'wp_ajax_wpse_form', 'ajax_wpse_form_action' );
add_action( 'wp_ajax_nopriv_wpse_form', 'ajax_wpse_form_action' );
```
AJAX
----
In your theme folder create an "ajax" folder with the file named wpse\_form.js. Paste into it this code.
```
jQuery(document).ready(function($) {
var wpse_form_btn = $('#wpse_form_submit_btn');
function init_wpse_form(){
/* VARS */
var form = $('#wpse_form'),
type = form.attr('method'),
requiredFields = ['wpse_form_10000 | textline'];
/* FUNCTIONS */
function showErrors(fieldsWithErrors){
form.find('.hasError').removeClass('hasError').end().find('.secureforms-error-msg.active').removeClass('active');
for(var i=0; i< fieldsWithErrors.length; i++){
if(fieldsWithErrors[i].length > 0){
$('#' + fieldsWithErrors[i]).addClass('hasError').next().addClass('active');
}
}
}
/* TRIGGER */
wpse_form_btn.on('click', function(e){
e.preventDefault();
e.stopPropagation();
if($('#check_wpse_form').val()){
return false;
} else {
var emptyErrors = [];
for(var i = 0; i<requiredFields.length; i++){
var fieldData = requiredFields[i].split(' | '),
field = $('#' + fieldData[0]),
fieldType = fieldData[1];
if(fieldType == 'select'){
var selected = field.find(':selected');
if(selected.length > 0){
if(selected.val() == 'wpse_form_select_null'){
emptyErrors.push(fieldData[0]);
}
} else {
emptyErrors.push(fieldData[0]);
}
} else if(fieldType == 'radio' || fieldType == 'checkbox'){
if(field.find('input:checked').length <= 0){
emptyErrors.push(fieldData[0]);
}
} else {
if(!field.val()){
emptyErrors.push(fieldData[0]);
}
}
}
if(emptyErrors.length > 0){
showErrors(emptyErrors);
$('#wpse_form_message_wrap').removeClass('success').addClass('error').text('Please fill all the required fields');
return false;
} else {
var data = form.serialize();
$.ajax({
type: type,
url: ajax_wpse_form.ajax_url,
data: data,
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#wpse_form_message_wrap')
.removeClass('error')
.addClass('success')
.text(response.return_message);
showErrors([]);
} else {
$('#wpse_form_message_wrap')
.removeClass('success')
.addClass('error')
.text(response.return_message);
showErrors(response.fields_with_errors);
}
},
error: function(xhr,err){
console.log("readyState: "+xhr.readyState+"\
status: "+xhr.status);
console.log("responseText: "+xhr.responseText);
}
})
}
}
});
};
if(wpse_form_btn.length > 0){
init_wpse_form();
}
});
```
JS
--
Paste this code into your theme's main js file.
```
$('body').on('click', 'input[type=radio]', function(){
var wrapper = $(this).parent(),
triggers = wrapper.find('.isTrigger');
if(triggers.length > 0){
triggers.each(function(){
if($(this).is(':checked')){
$('.' + $(this).attr('data-toggle')).slideDown(200);
} else {
$('.' + $(this).attr('data-toggle')).slideUp(200);
}
})
}
})
$('body').on('click', 'input[type=checkbox]', function(){
var that = $(this),
wrapper = that.parent(),
limit = wrapper.attr('data-limit'),
chosen = wrapper.find('input:checked').length;
// disabling / enabling choices
if(that.is(':checked')){
if(chosen + 1 > limit){
wrapper.find('input').not(':checked').prop('disabled', true);
}
} else {
wrapper.find('input').prop('disabled', false);
}
// conditional showing / hiding fields
if(that.hasClass('isTrigger')){
var targetClass = that.attr('data-toggle');
if(that.is(':checked')){
$('.' + targetClass).slideDown(200);
} else {
$('.' + targetClass).slideUp(200);
}
}
})
$('body').on('change', 'select', function(){
var that = $(this),
wrapper = that.parent(),
triggers = wrapper.find('.isTrigger'),
options = wrapper.find('option');
if(triggers.length > 0){
options.each(function(){
if($(this).is(':selected')){
if($(this).hasClass('isTrigger')){
$('.' + $(this).attr('data-toggle')).slideDown(200);
}
} else {
if($(this).hasClass('isTrigger')){
$('.' + $(this).attr('data-toggle')).slideUp(200);
}
}
})
}
})
```
CSS
---
Paste the code below into your theme's main css file.
```
form>div, form>p{
margin-top: 0;
margin-bottom: 1em;
}
form fieldset {
margin: 0;
border: none;
padding: 0;
}
form label, form legend{
display: block;
margin-bottom: .25em;
}
form label span, form legend span{
font-size: .8em;
font-style: italic;
}
form label span::before, form legend span::before{
content: '';
display: block;
}
input[type="checkbox"]+label, input[type="radio"]+label, input[type="number"]+label{
display: inline-block;
}
form .showOnTrigger{
display: none;
}
.secureforms-error-msg{
display: none;
color: red;
}
.secureforms-error-msg.active{
display: block;
}
.secureforms-hidden-wrapper{
display: none;
}
.secureforms-message-wrap.error{
border: 2px solid red;
}
.secureforms-message-wrap.success{
border: 2px solid green;
}
```
|
202,613 |
<p>I've enqueued a .js file on the "Media Library" page (upload.php). I need to hide and manipulate a few of the thumbnails on the page using JS only ( I'm not looking for workarounds ). </p>
<p>The elements on the page are being rendered by backbone and I have found no way so far to hook into it. In any window/document state, $('li.attachment').hide() function for example won't do it's job because of this.</p>
<p>I have tried going with the following piece of code, with no result so far, can't even debug the code because of unproperly hooking:</p>
<pre><code>window.wp = window.wp || {};
( function( $, _ ) {
var media = wp.media,
Attachments = media.model.Attachments,
Query = media.model.Query,
original = {};
original.AttachmentsBrowser = {
manipulate: media.view.AttachmentsBrowser.prototype.manipulate
};
_.extend( media.view.AttachmentsBrowser.prototype, {
initialize: function() {
original.AttachmentsBrowser.initialize.apply( this, arguments );
},
manipulate: function() {
var options = this.options,
self = this,
i = 1;
original.AttachmentsBrowser.manipulate.apply( this, arguments );
console.log('got here'); // Not outputting a thing
}
});
</code></pre>
<p>Any ideas how I should go about it? </p>
<p>Thanks a lot in advance!</p>
|
[
{
"answer_id": 202551,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": -1,
"selected": false,
"text": "<p>You have never read the WP documentation?</p>\n\n<p>Create any template and form and when submitting the form it could be</p>\n\n<p>Example:</p>\n\n<pre><code>$args = array('post_type'=>'post', 'post_title'=>'your title', 'post_status'=>'publish', 'post_content'=>'post content');\n\nwp_insert_post ($args);\n</code></pre>\n\n<p>This will allow any post page or custom post type to insert the post</p>\n"
},
{
"answer_id": 214743,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<p>This is pretty simple. So simple you need to make sure your guests don't insert bad code into you DB. So read up on <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow\">Data Validation</a> and <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow\">Validating Sanitizing and Escaping User Data</a> before you add anything to your site from a front-end form.</p>\n\n<ol>\n<li>Create a new page at <code>/new-post</code></li>\n<li>Create a page template to target that page</li>\n<li>Setup AJAX actions</li>\n<li>Render your form inside the custom page template.</li>\n<li>Use jQuery to submit the form details to AJAX</li>\n<li>AJAX action will validate the data</li>\n<li>If good, the new post will be created</li>\n<li>AJAX will output a success or fail response</li>\n<li>jQuery on the front-end form will inform the user of success or failure.</li>\n</ol>\n\n<p>First, create a page called <code>new-post</code> that will hold your form. Then create a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page\" rel=\"nofollow\">page template</a> to target that page using the file structure <code>page-{slug}.php</code>.</p>\n\n<pre><code>page-new-post.php\n</code></pre>\n\n<p>On that page you can check to see if <a href=\"https://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow\">is_user_logged_in</a> and if they have the ability to create posts using <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow\">current_user_can</a>. If not, you can always <a href=\"https://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\">wp_redirect</a> elsewhere or just <a href=\"https://codex.wordpress.org/Function_Reference/wp_die\" rel=\"nofollow\">wp_die</a>.</p>\n\n<p>You'll need to do all this with <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">AJAX</a> so create a front-end form that when clicked; submits data to WP, validates, and creates a new post. </p>\n\n<p>Take note of <code>_nopriv</code> which you don't want to use in your case because someone will SPAM your site to a crawl.</p>\n\n<pre><code>// AJAX for logged in users\n\nadd_action( 'wp_ajax_create_new_post', 'ajax_create_new_post_action' );\n\n// AJAX for non-logged in users\n\nadd_action( 'wp_ajax_nopriv_create_new_post', 'ajax_nopriv_create_new_post_action' );\n</code></pre>\n\n<p>Once you've collected the data and sanitized it in your <code>ajax_create_new_post_action</code> then you'll need to create a new post with <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow\">wp_insert_post</a>.</p>\n\n<hr>\n\n<p>Since there are quite a few steps involved I recommend generating most of this automatically using <a href=\"http://chrisplaneta.com/generators/wpsecureforms/\" rel=\"nofollow\">WP Secure Forms</a> and filling in the gaps after. Here is an example of an AJAX email submission form to give you a pretty good overview of the AJAX parts -- including sanitization.</p>\n\n<h2>Template for <a href=\"http://chrisplaneta.com/generators/wpsecureforms/\" rel=\"nofollow\">WP Secure Forms</a></h2>\n\n<pre><code>Title {30 characters limit}\n> * 30\n| Your Title\n! Field specific error message\n\n\nTextarea{150 characters limit}\n> 150\n| Content\n|\n|\n! Field specific error message\n\n\nThis label is invisible\n> H\n</code></pre>\n\n<h2>Form</h2>\n\n<p>This script goes into the PHP file of your theme.</p>\n\n<pre><code><p id=\"wpse_form_message_wrap\" class=\"secureforms-message-wrap\"></p>\n\n<form id=\"wpse_form\" method=\"post\">\n\n <div id=\"wpse_form_10000-wrapper\">\n <label for=\"wpse_form_10000\">* Title <span>30 characters limit</span></label>\n <input type=\"text\" name=\"wpse_form_10000\" id=\"wpse_form_10000\" value=\"\" placeholder=\"Your Title\" required=\"required\" maxlength=\"30\" />\n <p class=\"secureforms-error-msg\">Field specific error message</p>\n </div>\n\n <div id=\"wpse_form_20000-wrapper\">\n <label for=\"wpse_form_20000\">Textarea{150 characters limit}</label>\n <textarea rows=\"3\" name=\"wpse_form_20000\" id=\"wpse_form_20000\" value=\"\" maxlength=\"150\" ></textarea>\n <p class=\"secureforms-error-msg\">Field specific error message</p>\n </div>\n\n <div id=\"wpse_form_30000-wrapper\" class=\"secureforms-hidden-wrapper\">\n <input id=\"wpse_form_30000\" name=\"wpse_form_30000\" type=\"hidden\">\n </div>\n\n <div id=\"wpse_form_footer\">\n <input type=\"hidden\" id=\"check_wpse_form\" name=\"check_wpse_form\" value=\"\" />\n <input type=\"hidden\" name=\"action\" value=\"wpse_form\" />\n <?php echo wp_nonce_field('wpse_form', '_nonce_eklwu', true, false); ?>\n <input type=\"submit\" name=\"wpse_form_submit_btn\" id=\"wpse_form_submit_btn\" value=\"Submit\" />\n </div>\n\n</form>\n</code></pre>\n\n<h2>Functions.php</h2>\n\n<p>This one goes into your functions.php</p>\n\n<pre><code>// WP SECURE FORMS - EMAIL VALIDATION & SENDING \n\nrequire_once( 'ajax/wpse_form.php' );\n\n// WP SECURE FORMS - ENQUEUE EMAIL JS \n\nfunction enqueue_ajax_wpse_form() {\n\n if (!is_admin()) {\n wp_enqueue_script( 'ajax_wpse_form', get_template_directory_uri().'/ajax/wpse_form.js', array('jquery'), '', true );\n wp_localize_script( 'ajax_wpse_form', 'ajax_wpse_form', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n }\n}\n\nadd_action( 'wp_enqueue_scripts', 'enqueue_ajax_wpse_form', 999 );\n</code></pre>\n\n<h2>Validation</h2>\n\n<p>In your theme folder create an \"ajax\" folder with the file named wpse_form.php. Paste into it the code below.</p>\n\n<pre><code><?php \n\nfunction ajax_wpse_form_action() { \n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\"){ \n\n $return_message = '';\n $status = 'success';\n $fields_with_errors = array(); \n\n // validate nonce\n if(!wp_verify_nonce($_POST['_nonce_eklwu'], $_POST['action'])){\n $status = 'error';\n }\n\n // validate hidden field\n if(!empty(trim($_POST['check_wpse_form']))){\n $status = 'error';\n }\n\n if ($status == 'error') {\n $return_message = 'Data verification error. Check marked fields.';\n } else {\n\n $wpse_form_10000 = strip_tags(trim(stripslashes($_POST['wpse_form_10000'])));\n\n if(!empty($wpse_form_10000)){\n if(strlen($wpse_form_10000) > 30){\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_10000';\n }\n } else {\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_10000';\n }\n\n $wpse_form_20000 = strip_tags(trim(stripslashes($_POST['wpse_form_20000'])));\n\n if(!empty($wpse_form_20000)){\n if(strlen($wpse_form_20000) > 150){\n $status = 'error';\n $fields_with_errors[] = 'wpse_form_20000';\n }\n }\n\n $wpse_form_30000 = strip_tags(trim(stripslashes($_POST['wpse_form_30000'])));\n if ($status == 'error') {\n $return_message = 'Data verification error. Check marked fields.';\n } else {\n\n // message\n $to = '[email protected]';\n $header = 'From: '. get_bloginfo('name') . ' <[email protected]>'.PHP_EOL;\n $subject = 'Test Email Subject';\n $formMessage = '';\n\n $formMessage .= 'Title {30 characters limit}' . \"\\n\";\n $formMessage .= $wpse_form_10000 . \"\\n\\n\";\n $formMessage .= 'Textarea{150 characters limit}' . \"\\n\";\n $formMessage .= $wpse_form_20000 . \"\\n\\n\";\n $formMessage .= 'This label is invisible' . \"\\n\";\n $formMessage .= $wpse_form_30000 . \"\\n\\n\";\n if ( wp_mail($to, $subject, $formMessage, $header) ) {\n $return_message = 'Thank you for contacting us. We will get in touch as soon as possible.';\n } else {\n $status = 'error';\n $return_message = 'There was an error sending the message. Please try again.';\n }\n }\n }\n\n $resp = array(\n 'status' => $status,\n 'return_message' => $return_message,\n 'fields_with_errors' => $fields_with_errors,\n );\n\n header( \"Content-Type: application/json\" );\n echo json_encode($resp);\n die();\n\n} else {\n http_response_code(403);\n}\n}\n\nadd_action( 'wp_ajax_wpse_form', 'ajax_wpse_form_action' );\nadd_action( 'wp_ajax_nopriv_wpse_form', 'ajax_wpse_form_action' );\n</code></pre>\n\n<h2>AJAX</h2>\n\n<p>In your theme folder create an \"ajax\" folder with the file named wpse_form.js. Paste into it this code.</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n var wpse_form_btn = $('#wpse_form_submit_btn');\n\n function init_wpse_form(){\n\n /* VARS */\n\n var form = $('#wpse_form'),\n type = form.attr('method'),\n requiredFields = ['wpse_form_10000 | textline'];\n\n /* FUNCTIONS */\n\n function showErrors(fieldsWithErrors){\n\n form.find('.hasError').removeClass('hasError').end().find('.secureforms-error-msg.active').removeClass('active');\n\n for(var i=0; i< fieldsWithErrors.length; i++){\n if(fieldsWithErrors[i].length > 0){\n $('#' + fieldsWithErrors[i]).addClass('hasError').next().addClass('active');\n }\n }\n }\n\n /* TRIGGER */\n\n wpse_form_btn.on('click', function(e){\n\n e.preventDefault();\n e.stopPropagation();\n\n if($('#check_wpse_form').val()){\n return false;\n } else {\n\n var emptyErrors = [];\n\n for(var i = 0; i<requiredFields.length; i++){\n\n var fieldData = requiredFields[i].split(' | '),\n field = $('#' + fieldData[0]),\n fieldType = fieldData[1];\n\n if(fieldType == 'select'){\n var selected = field.find(':selected');\n if(selected.length > 0){\n if(selected.val() == 'wpse_form_select_null'){\n emptyErrors.push(fieldData[0]);\n }\n } else {\n emptyErrors.push(fieldData[0]);\n }\n } else if(fieldType == 'radio' || fieldType == 'checkbox'){\n if(field.find('input:checked').length <= 0){\n emptyErrors.push(fieldData[0]);\n }\n } else {\n if(!field.val()){\n emptyErrors.push(fieldData[0]);\n }\n }\n }\n\n if(emptyErrors.length > 0){\n showErrors(emptyErrors);\n $('#wpse_form_message_wrap').removeClass('success').addClass('error').text('Please fill all the required fields');\n return false;\n } else {\n\n var data = form.serialize();\n $.ajax({\n type: type,\n url: ajax_wpse_form.ajax_url,\n data: data,\n dataType: 'json',\n success: function(response) {\n\n if (response.status == 'success') {\n $('#wpse_form_message_wrap')\n .removeClass('error')\n .addClass('success')\n .text(response.return_message);\n\n showErrors([]);\n\n } else {\n $('#wpse_form_message_wrap')\n .removeClass('success')\n .addClass('error')\n .text(response.return_message);\n\n showErrors(response.fields_with_errors);\n }\n },\n error: function(xhr,err){\n console.log(\"readyState: \"+xhr.readyState+\"\\\nstatus: \"+xhr.status);\n console.log(\"responseText: \"+xhr.responseText);\n }\n })\n }\n }\n });\n };\n\n if(wpse_form_btn.length > 0){\n init_wpse_form();\n }\n\n});\n</code></pre>\n\n<h2>JS</h2>\n\n<p>Paste this code into your theme's main js file.</p>\n\n<pre><code>$('body').on('click', 'input[type=radio]', function(){\n\n var wrapper = $(this).parent(),\n triggers = wrapper.find('.isTrigger');\n\n if(triggers.length > 0){\n triggers.each(function(){\n if($(this).is(':checked')){\n $('.' + $(this).attr('data-toggle')).slideDown(200);\n } else {\n $('.' + $(this).attr('data-toggle')).slideUp(200);\n }\n })\n }\n\n})\n\n$('body').on('click', 'input[type=checkbox]', function(){\n\n var that = $(this),\n wrapper = that.parent(),\n limit = wrapper.attr('data-limit'),\n chosen = wrapper.find('input:checked').length;\n\n // disabling / enabling choices\n if(that.is(':checked')){\n if(chosen + 1 > limit){\n wrapper.find('input').not(':checked').prop('disabled', true);\n }\n } else {\n wrapper.find('input').prop('disabled', false);\n }\n\n // conditional showing / hiding fields\n if(that.hasClass('isTrigger')){\n\n var targetClass = that.attr('data-toggle');\n\n if(that.is(':checked')){\n $('.' + targetClass).slideDown(200);\n } else {\n $('.' + targetClass).slideUp(200);\n }\n }\n})\n\n$('body').on('change', 'select', function(){\n\n var that = $(this),\n wrapper = that.parent(),\n triggers = wrapper.find('.isTrigger'),\n options = wrapper.find('option');\n\n if(triggers.length > 0){\n options.each(function(){\n if($(this).is(':selected')){\n if($(this).hasClass('isTrigger')){\n $('.' + $(this).attr('data-toggle')).slideDown(200);\n }\n } else {\n if($(this).hasClass('isTrigger')){\n $('.' + $(this).attr('data-toggle')).slideUp(200);\n }\n }\n })\n }\n})\n</code></pre>\n\n<h2>CSS</h2>\n\n<p>Paste the code below into your theme's main css file.</p>\n\n<pre><code>form>div, form>p{\n margin-top: 0;\n margin-bottom: 1em;\n}\nform fieldset {\n margin: 0;\n border: none;\n padding: 0;\n}\nform label, form legend{\n display: block;\n margin-bottom: .25em;\n}\nform label span, form legend span{\n font-size: .8em;\n font-style: italic;\n}\nform label span::before, form legend span::before{\n content: '';\n display: block;\n}\ninput[type=\"checkbox\"]+label, input[type=\"radio\"]+label, input[type=\"number\"]+label{\n display: inline-block;\n}\nform .showOnTrigger{\n display: none;\n}\n.secureforms-error-msg{\n display: none;\n color: red;\n}\n.secureforms-error-msg.active{\n display: block;\n}\n.secureforms-hidden-wrapper{\n display: none;\n}\n.secureforms-message-wrap.error{\n border: 2px solid red;\n}\n.secureforms-message-wrap.success{\n border: 2px solid green;\n}\n</code></pre>\n"
}
] |
2015/09/14
|
[
"https://wordpress.stackexchange.com/questions/202613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62861/"
] |
I've enqueued a .js file on the "Media Library" page (upload.php). I need to hide and manipulate a few of the thumbnails on the page using JS only ( I'm not looking for workarounds ).
The elements on the page are being rendered by backbone and I have found no way so far to hook into it. In any window/document state, $('li.attachment').hide() function for example won't do it's job because of this.
I have tried going with the following piece of code, with no result so far, can't even debug the code because of unproperly hooking:
```
window.wp = window.wp || {};
( function( $, _ ) {
var media = wp.media,
Attachments = media.model.Attachments,
Query = media.model.Query,
original = {};
original.AttachmentsBrowser = {
manipulate: media.view.AttachmentsBrowser.prototype.manipulate
};
_.extend( media.view.AttachmentsBrowser.prototype, {
initialize: function() {
original.AttachmentsBrowser.initialize.apply( this, arguments );
},
manipulate: function() {
var options = this.options,
self = this,
i = 1;
original.AttachmentsBrowser.manipulate.apply( this, arguments );
console.log('got here'); // Not outputting a thing
}
});
```
Any ideas how I should go about it?
Thanks a lot in advance!
|
This is pretty simple. So simple you need to make sure your guests don't insert bad code into you DB. So read up on [Data Validation](https://codex.wordpress.org/Data_Validation) and [Validating Sanitizing and Escaping User Data](https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data) before you add anything to your site from a front-end form.
1. Create a new page at `/new-post`
2. Create a page template to target that page
3. Setup AJAX actions
4. Render your form inside the custom page template.
5. Use jQuery to submit the form details to AJAX
6. AJAX action will validate the data
7. If good, the new post will be created
8. AJAX will output a success or fail response
9. jQuery on the front-end form will inform the user of success or failure.
First, create a page called `new-post` that will hold your form. Then create a [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page) to target that page using the file structure `page-{slug}.php`.
```
page-new-post.php
```
On that page you can check to see if [is\_user\_logged\_in](https://codex.wordpress.org/Function_Reference/is_user_logged_in) and if they have the ability to create posts using [current\_user\_can](https://codex.wordpress.org/Function_Reference/current_user_can). If not, you can always [wp\_redirect](https://codex.wordpress.org/Function_Reference/wp_redirect) elsewhere or just [wp\_die](https://codex.wordpress.org/Function_Reference/wp_die).
You'll need to do all this with [AJAX](https://codex.wordpress.org/AJAX_in_Plugins) so create a front-end form that when clicked; submits data to WP, validates, and creates a new post.
Take note of `_nopriv` which you don't want to use in your case because someone will SPAM your site to a crawl.
```
// AJAX for logged in users
add_action( 'wp_ajax_create_new_post', 'ajax_create_new_post_action' );
// AJAX for non-logged in users
add_action( 'wp_ajax_nopriv_create_new_post', 'ajax_nopriv_create_new_post_action' );
```
Once you've collected the data and sanitized it in your `ajax_create_new_post_action` then you'll need to create a new post with [wp\_insert\_post](https://codex.wordpress.org/Function_Reference/wp_insert_post).
---
Since there are quite a few steps involved I recommend generating most of this automatically using [WP Secure Forms](http://chrisplaneta.com/generators/wpsecureforms/) and filling in the gaps after. Here is an example of an AJAX email submission form to give you a pretty good overview of the AJAX parts -- including sanitization.
Template for [WP Secure Forms](http://chrisplaneta.com/generators/wpsecureforms/)
---------------------------------------------------------------------------------
```
Title {30 characters limit}
> * 30
| Your Title
! Field specific error message
Textarea{150 characters limit}
> 150
| Content
|
|
! Field specific error message
This label is invisible
> H
```
Form
----
This script goes into the PHP file of your theme.
```
<p id="wpse_form_message_wrap" class="secureforms-message-wrap"></p>
<form id="wpse_form" method="post">
<div id="wpse_form_10000-wrapper">
<label for="wpse_form_10000">* Title <span>30 characters limit</span></label>
<input type="text" name="wpse_form_10000" id="wpse_form_10000" value="" placeholder="Your Title" required="required" maxlength="30" />
<p class="secureforms-error-msg">Field specific error message</p>
</div>
<div id="wpse_form_20000-wrapper">
<label for="wpse_form_20000">Textarea{150 characters limit}</label>
<textarea rows="3" name="wpse_form_20000" id="wpse_form_20000" value="" maxlength="150" ></textarea>
<p class="secureforms-error-msg">Field specific error message</p>
</div>
<div id="wpse_form_30000-wrapper" class="secureforms-hidden-wrapper">
<input id="wpse_form_30000" name="wpse_form_30000" type="hidden">
</div>
<div id="wpse_form_footer">
<input type="hidden" id="check_wpse_form" name="check_wpse_form" value="" />
<input type="hidden" name="action" value="wpse_form" />
<?php echo wp_nonce_field('wpse_form', '_nonce_eklwu', true, false); ?>
<input type="submit" name="wpse_form_submit_btn" id="wpse_form_submit_btn" value="Submit" />
</div>
</form>
```
Functions.php
-------------
This one goes into your functions.php
```
// WP SECURE FORMS - EMAIL VALIDATION & SENDING
require_once( 'ajax/wpse_form.php' );
// WP SECURE FORMS - ENQUEUE EMAIL JS
function enqueue_ajax_wpse_form() {
if (!is_admin()) {
wp_enqueue_script( 'ajax_wpse_form', get_template_directory_uri().'/ajax/wpse_form.js', array('jquery'), '', true );
wp_localize_script( 'ajax_wpse_form', 'ajax_wpse_form', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_wpse_form', 999 );
```
Validation
----------
In your theme folder create an "ajax" folder with the file named wpse\_form.php. Paste into it the code below.
```
<?php
function ajax_wpse_form_action() {
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$return_message = '';
$status = 'success';
$fields_with_errors = array();
// validate nonce
if(!wp_verify_nonce($_POST['_nonce_eklwu'], $_POST['action'])){
$status = 'error';
}
// validate hidden field
if(!empty(trim($_POST['check_wpse_form']))){
$status = 'error';
}
if ($status == 'error') {
$return_message = 'Data verification error. Check marked fields.';
} else {
$wpse_form_10000 = strip_tags(trim(stripslashes($_POST['wpse_form_10000'])));
if(!empty($wpse_form_10000)){
if(strlen($wpse_form_10000) > 30){
$status = 'error';
$fields_with_errors[] = 'wpse_form_10000';
}
} else {
$status = 'error';
$fields_with_errors[] = 'wpse_form_10000';
}
$wpse_form_20000 = strip_tags(trim(stripslashes($_POST['wpse_form_20000'])));
if(!empty($wpse_form_20000)){
if(strlen($wpse_form_20000) > 150){
$status = 'error';
$fields_with_errors[] = 'wpse_form_20000';
}
}
$wpse_form_30000 = strip_tags(trim(stripslashes($_POST['wpse_form_30000'])));
if ($status == 'error') {
$return_message = 'Data verification error. Check marked fields.';
} else {
// message
$to = '[email protected]';
$header = 'From: '. get_bloginfo('name') . ' <[email protected]>'.PHP_EOL;
$subject = 'Test Email Subject';
$formMessage = '';
$formMessage .= 'Title {30 characters limit}' . "\n";
$formMessage .= $wpse_form_10000 . "\n\n";
$formMessage .= 'Textarea{150 characters limit}' . "\n";
$formMessage .= $wpse_form_20000 . "\n\n";
$formMessage .= 'This label is invisible' . "\n";
$formMessage .= $wpse_form_30000 . "\n\n";
if ( wp_mail($to, $subject, $formMessage, $header) ) {
$return_message = 'Thank you for contacting us. We will get in touch as soon as possible.';
} else {
$status = 'error';
$return_message = 'There was an error sending the message. Please try again.';
}
}
}
$resp = array(
'status' => $status,
'return_message' => $return_message,
'fields_with_errors' => $fields_with_errors,
);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
} else {
http_response_code(403);
}
}
add_action( 'wp_ajax_wpse_form', 'ajax_wpse_form_action' );
add_action( 'wp_ajax_nopriv_wpse_form', 'ajax_wpse_form_action' );
```
AJAX
----
In your theme folder create an "ajax" folder with the file named wpse\_form.js. Paste into it this code.
```
jQuery(document).ready(function($) {
var wpse_form_btn = $('#wpse_form_submit_btn');
function init_wpse_form(){
/* VARS */
var form = $('#wpse_form'),
type = form.attr('method'),
requiredFields = ['wpse_form_10000 | textline'];
/* FUNCTIONS */
function showErrors(fieldsWithErrors){
form.find('.hasError').removeClass('hasError').end().find('.secureforms-error-msg.active').removeClass('active');
for(var i=0; i< fieldsWithErrors.length; i++){
if(fieldsWithErrors[i].length > 0){
$('#' + fieldsWithErrors[i]).addClass('hasError').next().addClass('active');
}
}
}
/* TRIGGER */
wpse_form_btn.on('click', function(e){
e.preventDefault();
e.stopPropagation();
if($('#check_wpse_form').val()){
return false;
} else {
var emptyErrors = [];
for(var i = 0; i<requiredFields.length; i++){
var fieldData = requiredFields[i].split(' | '),
field = $('#' + fieldData[0]),
fieldType = fieldData[1];
if(fieldType == 'select'){
var selected = field.find(':selected');
if(selected.length > 0){
if(selected.val() == 'wpse_form_select_null'){
emptyErrors.push(fieldData[0]);
}
} else {
emptyErrors.push(fieldData[0]);
}
} else if(fieldType == 'radio' || fieldType == 'checkbox'){
if(field.find('input:checked').length <= 0){
emptyErrors.push(fieldData[0]);
}
} else {
if(!field.val()){
emptyErrors.push(fieldData[0]);
}
}
}
if(emptyErrors.length > 0){
showErrors(emptyErrors);
$('#wpse_form_message_wrap').removeClass('success').addClass('error').text('Please fill all the required fields');
return false;
} else {
var data = form.serialize();
$.ajax({
type: type,
url: ajax_wpse_form.ajax_url,
data: data,
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#wpse_form_message_wrap')
.removeClass('error')
.addClass('success')
.text(response.return_message);
showErrors([]);
} else {
$('#wpse_form_message_wrap')
.removeClass('success')
.addClass('error')
.text(response.return_message);
showErrors(response.fields_with_errors);
}
},
error: function(xhr,err){
console.log("readyState: "+xhr.readyState+"\
status: "+xhr.status);
console.log("responseText: "+xhr.responseText);
}
})
}
}
});
};
if(wpse_form_btn.length > 0){
init_wpse_form();
}
});
```
JS
--
Paste this code into your theme's main js file.
```
$('body').on('click', 'input[type=radio]', function(){
var wrapper = $(this).parent(),
triggers = wrapper.find('.isTrigger');
if(triggers.length > 0){
triggers.each(function(){
if($(this).is(':checked')){
$('.' + $(this).attr('data-toggle')).slideDown(200);
} else {
$('.' + $(this).attr('data-toggle')).slideUp(200);
}
})
}
})
$('body').on('click', 'input[type=checkbox]', function(){
var that = $(this),
wrapper = that.parent(),
limit = wrapper.attr('data-limit'),
chosen = wrapper.find('input:checked').length;
// disabling / enabling choices
if(that.is(':checked')){
if(chosen + 1 > limit){
wrapper.find('input').not(':checked').prop('disabled', true);
}
} else {
wrapper.find('input').prop('disabled', false);
}
// conditional showing / hiding fields
if(that.hasClass('isTrigger')){
var targetClass = that.attr('data-toggle');
if(that.is(':checked')){
$('.' + targetClass).slideDown(200);
} else {
$('.' + targetClass).slideUp(200);
}
}
})
$('body').on('change', 'select', function(){
var that = $(this),
wrapper = that.parent(),
triggers = wrapper.find('.isTrigger'),
options = wrapper.find('option');
if(triggers.length > 0){
options.each(function(){
if($(this).is(':selected')){
if($(this).hasClass('isTrigger')){
$('.' + $(this).attr('data-toggle')).slideDown(200);
}
} else {
if($(this).hasClass('isTrigger')){
$('.' + $(this).attr('data-toggle')).slideUp(200);
}
}
})
}
})
```
CSS
---
Paste the code below into your theme's main css file.
```
form>div, form>p{
margin-top: 0;
margin-bottom: 1em;
}
form fieldset {
margin: 0;
border: none;
padding: 0;
}
form label, form legend{
display: block;
margin-bottom: .25em;
}
form label span, form legend span{
font-size: .8em;
font-style: italic;
}
form label span::before, form legend span::before{
content: '';
display: block;
}
input[type="checkbox"]+label, input[type="radio"]+label, input[type="number"]+label{
display: inline-block;
}
form .showOnTrigger{
display: none;
}
.secureforms-error-msg{
display: none;
color: red;
}
.secureforms-error-msg.active{
display: block;
}
.secureforms-hidden-wrapper{
display: none;
}
.secureforms-message-wrap.error{
border: 2px solid red;
}
.secureforms-message-wrap.success{
border: 2px solid green;
}
```
|
202,622 |
<p>I am currently in the course of migrating site content from an old pre 4.1 site to a new setup and hitting an issue with the rounding error issue of <a href="https://core.trac.wordpress.org/ticket/18532" rel="noreferrer">#18532</a> and the <a href="https://core.trac.wordpress.org/changeset/30660" rel="noreferrer">corresponding fix</a>.</p>
<p>To summarize this fixed a long standing rounding misbehaviour on the side of WordPress:</p>
<p>Imagine we upload an image with 693x173 and scale it to a width of 300:</p>
<ul>
<li>pre 4.1: 300x74</li>
<li>post 4.1: 300x75</li>
</ul>
<h2>The issue</h2>
<p>Generally this doesn't cause any issues because existing files and <code><img></code> aren't touched.</p>
<p>But when you regenerating thumbs or importing attachments from a WXR file they get generated differently in the filesystem leaving all <code><img></code> in <code>post_content</code> dead.</p>
<h2>Looking for a solution</h2>
<p>I have been thinking of various solutions:</p>
<h3>Going back to the bad old times</h3>
<p><a href="https://core.trac.wordpress.org/changeset/30660" rel="noreferrer">Changeset 30660</a> introduced a new filter <code>wp_constrain_dimensions</code> which can be used to just plug the old behaviour from before 4.1 back in. This does fix the issue.
But I am wondering if this might cause issues later on and generally I'd like to have the fix so although this works I'd deem it non-ideal.</p>
<h3>The Times They Are a-Changin'</h3>
<p>So this leaves us with another goal: Clean up the DB and replace all references to the old files with references to the new files. The question I am actually asking here now is how to do this. I am looking for an effective and generally-applicable solution as I suspect this issue does and will affect a lot of people</p>
<p>My current idea is this:</p>
<ol>
<li>Import, regenerate or whatever which leaves us with the new files and broken tags.</li>
<li>Create a list A from all resized files in the filesystem or alternatively getting this information from the database</li>
<li>Parse this list and create a second list B with filenames all offset by one pixel as it would look before 4.1</li>
<li>Do a search&replace over the whole database replacing all occurences of B with the relating entry in A</li>
</ol>
<p>I am just not sure if this is the most smart and efficient way to handle this situation. It also feels a bit too brute-force. So before implementing it I just wanted to check with the infinite wisdom of the WPSE crowd ;)</p>
<p><em>[edit] Having read <a href="https://wordpress.stackexchange.com/users/35923/ck-macleod">ck-macleod</a>s answer (thanks!) I think a fix should solve this once and for all so you do not need to constantly keep this issue in the back of your head. [/edit]</em></p>
<p><em>[edit2] I just found a <a href="https://core.trac.wordpress.org/ticket/31581" rel="noreferrer">related ticket on Trac</a>. Adding for reference. [/edit2]</em></p>
|
[
{
"answer_id": 202907,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Solving the problem globally and perfectly for ALL image files (and links) in a large site - given the possibility, for instance, that individuals may have occasionally renamed image files manually imitating the WP style - and other odd variations - might be difficult. Database search and replace operations are also going involve complications (and risks!). </p>\n\n<p>Could you handle the vast majority of errors - broken images and broken image links, I presume - and achieve the desired end result or reasonable facsimile, by the following method?</p>\n\n<ol>\n<li><p>Identify the date before which all resized images where resized by the old \"intval\" method rather than the new \"round\" method. (A different kind of cut-off could also be created, but date seems easiest.)</p></li>\n<li><p>For all posts published <= the cut-off-date, run preg_replace on the_content() at load/render time, capturing all image files with the problem pattern or patterns and replacing them with the desired pattern. The database would remain unaltered, but the output would be error-free in the most instances. I'm not sure whether the solution would need to apply both to \"singular\" page post content and to archive pages and other processes as well.</p></li>\n</ol>\n\n<p>If a solution of this type would be helpful, then the next question would be whether the problem patterns and replacements could be adequately defined. It looks from your list of proposed solutions that possibly a few typical patterns could in fact be isolated (perhaps taken from prior media settings producing thumbnails and some other images). </p>\n\n<p>I have already written a simpler function that I use (and am in the process of turning into a plug-in), that globally replaces all image files in designated directories, up to a certain date, with a default image or image-link, as per the above-described method. It was a for a site where, in an excess of copyright caution, the operators simply deleted all of their images, unaware that, in addition to producing ugly results on old pages, they were also turning out thousands of errors, two each for each image. </p>\n\n<p>If you can narrow down the problem pattern more specifically, and the instances where the output would need to be altered, then I could see about plugging it into my format - which isn't very complicated, and which for a better RegExer than I might even be easy. On the other hand, I wouldn't want to waste your or my time if this approach would not answer the problem for you.</p>\n"
},
{
"answer_id": 206986,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p>Okay this is a basic approach on replacing broken images on the fly. Be aware that this is more a proof of concept than a battle-tested solution. It just hooks on the <code>the_content</code> filter which might (probably has) some unwanted side-effects in some situations. Handle with care. :)</p>\n\n<p>Although it says so in the code too I also want to credit <a href=\"https://wordpress.stackexchange.com/users/847/rarst\">@Rarst</a> for <a href=\"https://wordpress.stackexchange.com/a/7094/47733\">this answer</a> used in my code.</p>\n\n<pre><code>/*\nPlugin Name: Bugfix 31581 Live\nPlugin URI: https://wordpress.stackexchange.com/a/206986/47733\nDescription: Fixes image references in post content after post 4.1 image scaling change (see https://core.trac.wordpress.org/ticket/31581)\nVersion: 0.0.1\n*/\n\nclass Bugfix31581Live {\n\n protected $matchURLs;\n protected $matchFiles;\n\n protected $remaps;\n\n public function init(){\n\n $filetypes = $this->get_allowed_image_extentions();\n\n $baseurl = wp_upload_dir();\n $baseurl = preg_quote($baseurl['baseurl'], '/');\n\n $this->matchURLs = '/' . $baseurl . '\\/.??([a-zA-Z0-9_-]*?\\.(?:' . $filetypes . '))/';\n\n //TODO: This pattern can be different. See `image_make_intermediate_size` in image editor implementation\n $this->matchFiles = '/([0-9]{1,4})x([0-9]{1,4}).(' . $filetypes . ')$/';\n\n add_filter('the_content', array($this, 'update_urls') );\n }\n\n public function update_urls($content){\n\n $urls = array();\n\n preg_match_all($this->matchURLs,$content,$urls);\n\n // Bail out early if we don't have any match.\n if($urls === false || empty($urls[0])){\n return $content;\n }\n\n // Loop through all matches\n foreach($urls[0] as $url){\n\n // Try to resolve this URL to an attachment ID\n $id = $this->get_attachment_id($url);\n\n // If not let's see if this might be a URL that has been broken by our beloved Changeset 30660\n if( $id === false ){\n\n $dimensions = array();\n\n // Extract the dimensions\n preg_match($this->matchFiles,$url,$dimensions);\n\n // If the file URL doesn't allow guessing the dimensions bail out.\n if(empty($dimensions)){\n continue;\n }\n\n // Old filename\n $old = $dimensions[1] . 'x' . $dimensions[2] . '.' . $dimensions[3];\n\n // New filename (not sure if this exists yet)\n $new = $dimensions[1] . 'x' . ($dimensions[2]+1) . '.' . $dimensions[3];\n\n // Build the new URL (not sure if this exists yet)\n $new_url = str_replace($old,$new,$url);\n\n // Try to get the attachment with the new url\n $id = $this->get_attachment_id($new_url);\n\n // Bad luck. This also doesn't exist.\n if( $id === false ) {\n continue;\n }\n\n // Just to be sure everything is in sync we get the URL built from id and size.\n $db_url = wp_get_attachment_image_src($id,array($dimensions[1], $dimensions[2]+1));\n\n // Check if the URL we created and the one wp_get_attachment_image_src builds are the same.\n if($new_url === $db_url[0]){\n\n // Awesome let's replace the broken URL.\n $content = str_replace($url,$new_url,$content);\n }\n\n }\n\n }\n\n return $content;\n }\n\n /**\n * Get the Attachment ID for a given image URL.\n *\n * @link https://wordpress.stackexchange.com/a/7094\n *\n * @param string $url\n *\n * @return boolean|integer\n */\n protected function get_attachment_id( $url ) {\n\n $dir = wp_upload_dir();\n\n // baseurl never has a trailing slash\n if ( false === strpos( $url, $dir['baseurl'] . '/' ) ) {\n // URL points to a place outside of upload directory\n return false;\n }\n\n $file = basename( $url );\n $query = array(\n 'post_type' => 'attachment',\n 'fields' => 'ids',\n 'meta_query' => array(\n array(\n 'value' => $file,\n 'compare' => 'LIKE',\n ),\n )\n );\n\n $query['meta_query'][0]['key'] = '_wp_attached_file';\n\n // query attachments\n $ids = get_posts( $query );\n\n if ( ! empty( $ids ) ) {\n\n foreach ( $ids as $id ) {\n\n $tmp = wp_get_attachment_image_src( $id, 'full' );\n\n // first entry of returned array is the URL\n if ( $url === array_shift( $tmp ) )\n return $id;\n }\n }\n\n $query['meta_query'][0]['key'] = '_wp_attachment_metadata';\n\n // query attachments again\n $ids = get_posts( $query );\n\n if ( empty( $ids) )\n return false;\n\n foreach ( $ids as $id ) {\n\n $meta = wp_get_attachment_metadata( $id );\n\n foreach ( $meta['sizes'] as $size => $values ) {\n\n $tmp = wp_get_attachment_image_src( $id, $size );\n\n if ( $values['file'] === $file && $url === array_shift( $tmp ) )\n return $id;\n }\n }\n\n return false;\n }\n\n protected function get_allowed_image_extentions(){\n $allowed_filetypes = get_allowed_mime_types();\n\n $allowed_images = array();\n\n foreach($allowed_filetypes as $extensions => $mimetype){\n if( substr($mimetype,0,6) == 'image/' ){\n $allowed_images[] = $extensions;\n }\n }\n\n return implode('|',$allowed_images);\n }\n\n}\n\nadd_filter('init',array(new Bugfix31581Live(),'init'));\n</code></pre>\n"
},
{
"answer_id": 206992,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 2,
"selected": false,
"text": "<p>This is another approach than <a href=\"https://wordpress.stackexchange.com/a/206986/47733\">the other answer</a> that works when importing content with the importer and fixes the URLs once and for all. Again: This is not battle-tested but is the solution I settled on and it did work.</p>\n\n<p>I prefer this as it solves the issue once and for all and if it works, it works. As you are not leaving broken stuff in the DB and fix it on display you do not need to worry about stuff breaking later on.</p>\n\n<pre><code>/*\nPlugin Name: Bugfix Ticket 31581 for WP_Importer\nPlugin URI: https://wordpress.stackexchange.com/a/206992/47733\nDescription: Fixes image references after post WP 4.1 image scaling change in post content when using the WP_Importer (see https://core.trac.wordpress.org/ticket/31581)\nVersion: 0.0.1\n*/\n\nclass Bugfix31581WPImporter {\n\n protected $remaps;\n\n /**\n * Initialize class, mainly setting up hooks\n */\n public function init(){\n\n if (WP_IMPORTING === true){\n\n $this->remaps = array();\n\n //This hook is chosen because it is pretty close to where the actual attachment import is happening.\n //TODO: May be reconsidered.\n add_filter('wp_update_attachment_metadata', array($this, 'collectRemaps'), 10 , 2);\n\n add_action('import_end', array($this, 'remap'));\n add_action('import_end', array($this, 'importEnded'));\n }\n\n }\n\n /**\n * Cleans up hooks after the import has ended.\n */\n public function importEnded(){\n remove_filter('wp_update_attachment_metadata', array($this, 'collectRemaps'), 10);\n\n remove_action('import_end', array($this, 'remap'), 10);\n remove_action('import_end', array($this, 'importEnded'), 10);\n }\n\n /**\n * When an attachment is added compare the resulting sizes with the sizes from the legacy algorithm and setup remap.\n *\n * @param $data\n * @param $post_id\n *\n * @return mixed\n */\n public function collectRemaps($data, $post_id ){\n\n $intermediate_sizes = $this->getIntermediateSizes();\n\n if(empty($data) || !array_key_exists('sizes', $data)){\n return $data;\n }\n\n foreach($data['sizes'] as $key => $size){\n\n $size_new_algorithm = array($size['width'], $size['height']);\n\n $dest_w = $intermediate_sizes[$key]['width'];\n $dest_h = $intermediate_sizes[$key]['height'];\n $crop = $intermediate_sizes[$key]['crop'];\n\n add_filter('wp_constrain_dimensions', array($this, 'legacy_wp_constrain_dimensions'), 10, 5);\n\n $size_old_algorithm = image_resize_dimensions($data['width'], $data['height'], $dest_w, $dest_h, $crop);\n\n //Bail out in the rare case of `image_resize_dimensions` returning false\n if($size_old_algorithm===false){\n continue;\n }\n\n $size_old_algorithm = array($size_old_algorithm[4], $size_old_algorithm[5]);\n\n remove_filter('wp_constrain_dimensions', array($this, 'legacy_wp_constrain_dimensions'), 10);\n\n // Compare the current size with the calculation of the old algorithm...\n $diff = array_diff($size_new_algorithm, $size_old_algorithm);\n\n // ...to detect any mismatches\n if(!empty($diff)){\n\n $oldFilename = $this->getOldFilename($size['file'], $size_old_algorithm);\n\n // If getting the old filename didn't work for some reason (probably other filename-structure) bail out.\n if($oldFilename===false){\n continue;\n }\n\n if(!array_key_exists($post_id, $this->remaps)){\n $this->remaps[$post_id] = array();\n }\n\n $this->remaps[$post_id][$size['file']] = array(\n 'file' => $oldFilename,\n 'size' => $key\n );\n }\n\n }\n\n return $data;\n }\n\n /**\n * Get resize settings for all image sizes\n *\n * Taken from wp_generate_attachment_metadata() in includes/image.php\n *\n * @return array\n */\n public function getIntermediateSizes(){\n\n global $_wp_additional_image_sizes;\n\n $sizes = array();\n foreach ( get_intermediate_image_sizes() as $s ) {\n $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );\n if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )\n $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes\n else\n $sizes[$s]['width'] = get_option( \"{$s}_size_w\" ); // For default sizes set in options\n if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )\n $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes\n else\n $sizes[$s]['height'] = get_option( \"{$s}_size_h\" ); // For default sizes set in options\n if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )\n $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop']; // For theme-added sizes\n else\n $sizes[$s]['crop'] = get_option( \"{$s}_crop\" ); // For default sizes set in options\n }\n\n return $sizes;\n }\n\n /**\n * Turn the new filename into the old filename reducing the height by one\n *\n * @param $newFilename\n * @param $size\n *\n * @return mixed\n */\n public function getOldFilename($newFilename, $size){\n\n $dimensions = array();\n\n $filetypes = $this->getAllowedImageExtentions();\n\n // TODO: This pattern can be different. See `image_make_intermediate_size` in image editor implementation.\n $matchFiles = '/([0-9]{1,5})x([0-9]{1,5}).(' . $filetypes . ')$/';\n\n // Extract the dimensions\n preg_match($matchFiles,$newFilename,$dimensions);\n\n // If the file URL doesn't allow guessing the dimensions bail out.\n if(empty($dimensions)){\n return $newFilename;\n }\n\n $newStub = $dimensions[1] . 'x' . $dimensions[2] . '.' . $dimensions[3];\n\n $oldStub = $size[0] . 'x' . $size[1] . '.' . $dimensions[3];\n\n $oldFilename = str_replace($newStub,$oldStub,$newFilename);\n\n return $oldFilename;\n }\n\n /**\n * Extract all file extensions that match an image/* mime type\n *\n * @return string\n */\n protected function getAllowedImageExtentions(){\n $allowed_filetypes = get_allowed_mime_types();\n\n $allowed_images = array();\n\n foreach($allowed_filetypes as $extensions => $mimetype){\n if( substr($mimetype,0,6) == 'image/' ){\n $allowed_images[] = $extensions;\n }\n }\n\n return implode('|',$allowed_images);\n }\n\n\n /**\n * This is the heart of this class. Based on the collected remaps from earlier it does a S&R on the DB.\n */\n public function remap(){\n\n global $wpdb;\n\n foreach($this->remaps as $attachment_id => $replaces){\n\n foreach($replaces as $new_url => $old_data){\n\n $to_url = wp_get_attachment_image_src($attachment_id,$old_data['size']);\n $to_url = $to_url[0];\n\n $from_url = str_replace($new_url, $old_data['file'], $to_url);\n\n // remap urls in post_content\n $wpdb->query( $wpdb->prepare(\"UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)\", $from_url, $to_url) );\n\n //TODO: This is disabled as enclosures can't be images, right?\n // remap enclosure urls\n //$result = $wpdb->query( $wpdb->prepare(\"UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'\", $from_url, $to_url) );\n\n }\n\n }\n\n }\n\n /**\n * This is a copy of the legacy pre 4.1 wp_constrain_dimensions()\n *\n * @param $dimensions\n * @param $current_width\n * @param $current_height\n * @param $max_width\n * @param $max_height\n *\n * @return array\n */\n public function legacy_wp_constrain_dimensions($dimensions, $current_width, $current_height, $max_width, $max_height){\n if ( !$max_width and !$max_height )\n return array( $current_width, $current_height );\n\n $width_ratio = $height_ratio = 1.0;\n $did_width = $did_height = false;\n\n if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {\n $width_ratio = $max_width / $current_width;\n $did_width = true;\n }\n\n if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {\n $height_ratio = $max_height / $current_height;\n $did_height = true;\n }\n\n // Calculate the larger/smaller ratios\n $smaller_ratio = min( $width_ratio, $height_ratio );\n $larger_ratio = max( $width_ratio, $height_ratio );\n\n if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )\n // The larger ratio is too big. It would result in an overflow.\n $ratio = $smaller_ratio;\n else\n // The larger ratio fits, and is likely to be a more \"snug\" fit.\n $ratio = $larger_ratio;\n\n // Very small dimensions may result in 0, 1 should be the minimum.\n $w = max ( 1, intval( $current_width * $ratio ) );\n $h = max ( 1, intval( $current_height * $ratio ) );\n\n // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short\n // We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.\n // Thus we look for dimensions that are one pixel shy of the max value and bump them up\n if ( $did_width && $w == $max_width - 1 )\n $w = $max_width; // Round it up\n if ( $did_height && $h == $max_height - 1 )\n $h = $max_height; // Round it up\n\n return array( $w, $h );\n }\n\n}\n\nadd_filter('import_start',array(new Bugfix31581WPImporter(),'init'));\n</code></pre>\n"
}
] |
2015/09/14
|
[
"https://wordpress.stackexchange.com/questions/202622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47733/"
] |
I am currently in the course of migrating site content from an old pre 4.1 site to a new setup and hitting an issue with the rounding error issue of [#18532](https://core.trac.wordpress.org/ticket/18532) and the [corresponding fix](https://core.trac.wordpress.org/changeset/30660).
To summarize this fixed a long standing rounding misbehaviour on the side of WordPress:
Imagine we upload an image with 693x173 and scale it to a width of 300:
* pre 4.1: 300x74
* post 4.1: 300x75
The issue
---------
Generally this doesn't cause any issues because existing files and `<img>` aren't touched.
But when you regenerating thumbs or importing attachments from a WXR file they get generated differently in the filesystem leaving all `<img>` in `post_content` dead.
Looking for a solution
----------------------
I have been thinking of various solutions:
### Going back to the bad old times
[Changeset 30660](https://core.trac.wordpress.org/changeset/30660) introduced a new filter `wp_constrain_dimensions` which can be used to just plug the old behaviour from before 4.1 back in. This does fix the issue.
But I am wondering if this might cause issues later on and generally I'd like to have the fix so although this works I'd deem it non-ideal.
### The Times They Are a-Changin'
So this leaves us with another goal: Clean up the DB and replace all references to the old files with references to the new files. The question I am actually asking here now is how to do this. I am looking for an effective and generally-applicable solution as I suspect this issue does and will affect a lot of people
My current idea is this:
1. Import, regenerate or whatever which leaves us with the new files and broken tags.
2. Create a list A from all resized files in the filesystem or alternatively getting this information from the database
3. Parse this list and create a second list B with filenames all offset by one pixel as it would look before 4.1
4. Do a search&replace over the whole database replacing all occurences of B with the relating entry in A
I am just not sure if this is the most smart and efficient way to handle this situation. It also feels a bit too brute-force. So before implementing it I just wanted to check with the infinite wisdom of the WPSE crowd ;)
*[edit] Having read [ck-macleod](https://wordpress.stackexchange.com/users/35923/ck-macleod)s answer (thanks!) I think a fix should solve this once and for all so you do not need to constantly keep this issue in the back of your head. [/edit]*
*[edit2] I just found a [related ticket on Trac](https://core.trac.wordpress.org/ticket/31581). Adding for reference. [/edit2]*
|
This is another approach than [the other answer](https://wordpress.stackexchange.com/a/206986/47733) that works when importing content with the importer and fixes the URLs once and for all. Again: This is not battle-tested but is the solution I settled on and it did work.
I prefer this as it solves the issue once and for all and if it works, it works. As you are not leaving broken stuff in the DB and fix it on display you do not need to worry about stuff breaking later on.
```
/*
Plugin Name: Bugfix Ticket 31581 for WP_Importer
Plugin URI: https://wordpress.stackexchange.com/a/206992/47733
Description: Fixes image references after post WP 4.1 image scaling change in post content when using the WP_Importer (see https://core.trac.wordpress.org/ticket/31581)
Version: 0.0.1
*/
class Bugfix31581WPImporter {
protected $remaps;
/**
* Initialize class, mainly setting up hooks
*/
public function init(){
if (WP_IMPORTING === true){
$this->remaps = array();
//This hook is chosen because it is pretty close to where the actual attachment import is happening.
//TODO: May be reconsidered.
add_filter('wp_update_attachment_metadata', array($this, 'collectRemaps'), 10 , 2);
add_action('import_end', array($this, 'remap'));
add_action('import_end', array($this, 'importEnded'));
}
}
/**
* Cleans up hooks after the import has ended.
*/
public function importEnded(){
remove_filter('wp_update_attachment_metadata', array($this, 'collectRemaps'), 10);
remove_action('import_end', array($this, 'remap'), 10);
remove_action('import_end', array($this, 'importEnded'), 10);
}
/**
* When an attachment is added compare the resulting sizes with the sizes from the legacy algorithm and setup remap.
*
* @param $data
* @param $post_id
*
* @return mixed
*/
public function collectRemaps($data, $post_id ){
$intermediate_sizes = $this->getIntermediateSizes();
if(empty($data) || !array_key_exists('sizes', $data)){
return $data;
}
foreach($data['sizes'] as $key => $size){
$size_new_algorithm = array($size['width'], $size['height']);
$dest_w = $intermediate_sizes[$key]['width'];
$dest_h = $intermediate_sizes[$key]['height'];
$crop = $intermediate_sizes[$key]['crop'];
add_filter('wp_constrain_dimensions', array($this, 'legacy_wp_constrain_dimensions'), 10, 5);
$size_old_algorithm = image_resize_dimensions($data['width'], $data['height'], $dest_w, $dest_h, $crop);
//Bail out in the rare case of `image_resize_dimensions` returning false
if($size_old_algorithm===false){
continue;
}
$size_old_algorithm = array($size_old_algorithm[4], $size_old_algorithm[5]);
remove_filter('wp_constrain_dimensions', array($this, 'legacy_wp_constrain_dimensions'), 10);
// Compare the current size with the calculation of the old algorithm...
$diff = array_diff($size_new_algorithm, $size_old_algorithm);
// ...to detect any mismatches
if(!empty($diff)){
$oldFilename = $this->getOldFilename($size['file'], $size_old_algorithm);
// If getting the old filename didn't work for some reason (probably other filename-structure) bail out.
if($oldFilename===false){
continue;
}
if(!array_key_exists($post_id, $this->remaps)){
$this->remaps[$post_id] = array();
}
$this->remaps[$post_id][$size['file']] = array(
'file' => $oldFilename,
'size' => $key
);
}
}
return $data;
}
/**
* Get resize settings for all image sizes
*
* Taken from wp_generate_attachment_metadata() in includes/image.php
*
* @return array
*/
public function getIntermediateSizes(){
global $_wp_additional_image_sizes;
$sizes = array();
foreach ( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
$sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
else
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
$sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
else
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
$sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop']; // For theme-added sizes
else
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
return $sizes;
}
/**
* Turn the new filename into the old filename reducing the height by one
*
* @param $newFilename
* @param $size
*
* @return mixed
*/
public function getOldFilename($newFilename, $size){
$dimensions = array();
$filetypes = $this->getAllowedImageExtentions();
// TODO: This pattern can be different. See `image_make_intermediate_size` in image editor implementation.
$matchFiles = '/([0-9]{1,5})x([0-9]{1,5}).(' . $filetypes . ')$/';
// Extract the dimensions
preg_match($matchFiles,$newFilename,$dimensions);
// If the file URL doesn't allow guessing the dimensions bail out.
if(empty($dimensions)){
return $newFilename;
}
$newStub = $dimensions[1] . 'x' . $dimensions[2] . '.' . $dimensions[3];
$oldStub = $size[0] . 'x' . $size[1] . '.' . $dimensions[3];
$oldFilename = str_replace($newStub,$oldStub,$newFilename);
return $oldFilename;
}
/**
* Extract all file extensions that match an image/* mime type
*
* @return string
*/
protected function getAllowedImageExtentions(){
$allowed_filetypes = get_allowed_mime_types();
$allowed_images = array();
foreach($allowed_filetypes as $extensions => $mimetype){
if( substr($mimetype,0,6) == 'image/' ){
$allowed_images[] = $extensions;
}
}
return implode('|',$allowed_images);
}
/**
* This is the heart of this class. Based on the collected remaps from earlier it does a S&R on the DB.
*/
public function remap(){
global $wpdb;
foreach($this->remaps as $attachment_id => $replaces){
foreach($replaces as $new_url => $old_data){
$to_url = wp_get_attachment_image_src($attachment_id,$old_data['size']);
$to_url = $to_url[0];
$from_url = str_replace($new_url, $old_data['file'], $to_url);
// remap urls in post_content
$wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url) );
//TODO: This is disabled as enclosures can't be images, right?
// remap enclosure urls
//$result = $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url) );
}
}
}
/**
* This is a copy of the legacy pre 4.1 wp_constrain_dimensions()
*
* @param $dimensions
* @param $current_width
* @param $current_height
* @param $max_width
* @param $max_height
*
* @return array
*/
public function legacy_wp_constrain_dimensions($dimensions, $current_width, $current_height, $max_width, $max_height){
if ( !$max_width and !$max_height )
return array( $current_width, $current_height );
$width_ratio = $height_ratio = 1.0;
$did_width = $did_height = false;
if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
$width_ratio = $max_width / $current_width;
$did_width = true;
}
if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
$height_ratio = $max_height / $current_height;
$did_height = true;
}
// Calculate the larger/smaller ratios
$smaller_ratio = min( $width_ratio, $height_ratio );
$larger_ratio = max( $width_ratio, $height_ratio );
if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
// The larger ratio is too big. It would result in an overflow.
$ratio = $smaller_ratio;
else
// The larger ratio fits, and is likely to be a more "snug" fit.
$ratio = $larger_ratio;
// Very small dimensions may result in 0, 1 should be the minimum.
$w = max ( 1, intval( $current_width * $ratio ) );
$h = max ( 1, intval( $current_height * $ratio ) );
// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
// We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.
// Thus we look for dimensions that are one pixel shy of the max value and bump them up
if ( $did_width && $w == $max_width - 1 )
$w = $max_width; // Round it up
if ( $did_height && $h == $max_height - 1 )
$h = $max_height; // Round it up
return array( $w, $h );
}
}
add_filter('import_start',array(new Bugfix31581WPImporter(),'init'));
```
|
202,629 |
<p>I am trying to include bootstrap only when the short-code function executes. It gets included but it affects the other tags of the theme.</p>
<p>The only way I can get around this is including bootstrap globally in the plugin's primary file. It works on the front end, making the short-code execute and display output with bootstrap classes and all of the other page content is not affected by bootstrap. </p>
<p>But this way, these are included everywhere and this affects the back-end styles. </p>
<p>The problem is tied to both front and back ends. If one is fixed, the other gets broken. </p>
|
[
{
"answer_id": 202635,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": 0,
"selected": false,
"text": "<p>First outside your shortcode callback function just register the stylsheet and then in shortcode callback function enqueue it. like:-</p>\n\n<pre><code> function wpsoe_191512_avatar_shortcode_wp_enqueue_scripts() {\n wp_register_style( 'get-avatar-style', plugins_url( '/css/style.css' , __FILE__ ), array(), '1.0.0', all );\n }\n\n\n add_action( 'wp_enqueue_scripts', 'brw_avatar_shortcode_wp_enqueue_scripts' );\n\n if ( function_exists( 'get_avatar' ) ) {\n\n function wpse_165754_user_avatar_shortcode ( $attributes ) {\n global $current_user;\n get_currentuserinfo();\n extract(shortcode_atts(array(\n \"id\" => $current_user->ID,\n \"size\" => 32,\n \"default\" => 'mystery',\n \"alt\" => '',\n \"class\" => '',\n ), \n $attributes, 'get_avatar' ));\n $get_avatar= get_avatar( $id, $size, $default, $alt );\n\n wp_enqueue_style( 'get-avatar-style' );\n\n return '<span class=\"get_avatar '.$class.'\">'.$get_avatar.'</span>';\n }\n add_shortcode ('get_avatar', 'wpse_165754_user_avatar_shortcode');\n }\n</code></pre>\n\n<p>Above is the example. You can use yours.\nThanks</p>\n"
},
{
"answer_id": 202660,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>I also find the typical practice of queuing globally or from inside shortcodes problematic.</p>\n\n<p>I had a similar challenge with implementing code highlight on my site — I only wanted scripts and style to load as necessary. I ended up checking content for <code><pre></code> tag as condition to output:</p>\n\n<pre><code>{% if '<pre>' in get_the_content() %}\n <link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/solarized_dark.min.css\">\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js\"></script>\n {% if has_term( 'twig', 'post_tag' ) %}\n <script src=\"//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/languages/twig.min.js\"></script>\n {% endif %}\n <script type=\"text/javascript\">\n jQuery(document).ready(function ($) {\n $('pre').each(function (i, e) {\n hljs.highlightBlock(e)\n });\n });\n </script>\n{% endif %}\n</code></pre>\n\n<p>This is in Twig template (and doesn't use WP queue), but you can use same approach in PHP just as well.</p>\n"
}
] |
2015/09/14
|
[
"https://wordpress.stackexchange.com/questions/202629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65650/"
] |
I am trying to include bootstrap only when the short-code function executes. It gets included but it affects the other tags of the theme.
The only way I can get around this is including bootstrap globally in the plugin's primary file. It works on the front end, making the short-code execute and display output with bootstrap classes and all of the other page content is not affected by bootstrap.
But this way, these are included everywhere and this affects the back-end styles.
The problem is tied to both front and back ends. If one is fixed, the other gets broken.
|
I also find the typical practice of queuing globally or from inside shortcodes problematic.
I had a similar challenge with implementing code highlight on my site — I only wanted scripts and style to load as necessary. I ended up checking content for `<pre>` tag as condition to output:
```
{% if '<pre>' in get_the_content() %}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/solarized_dark.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
{% if has_term( 'twig', 'post_tag' ) %}
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/languages/twig.min.js"></script>
{% endif %}
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('pre').each(function (i, e) {
hljs.highlightBlock(e)
});
});
</script>
{% endif %}
```
This is in Twig template (and doesn't use WP queue), but you can use same approach in PHP just as well.
|
202,709 |
<p>I have split my post content into mutiple pages using the <code><! - nextpage -></code> code. I want to give my paginated links their own title instead of the regular 1,2,3. How can I do this? cause on this doc <a href="https://codex.wordpress.org/Styling_Page-Links">https://codex.wordpress.org/Styling_Page-Links</a> it only mentions method to adding suffix or prefix. I just want to give each paged number their own custom title</p>
|
[
{
"answer_id": 227012,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 3,
"selected": false,
"text": "<p>You can use filter <a href=\"https://developer.wordpress.org/reference/hooks/wp_link_pages_link/\"><code>wp_link_pages_link</code></a></p>\n\n<p>First pass our custom string placeholder (This can be anything you like except string containing <code>%</code>, just for now I am using <code>#custom_title#</code>).</p>\n\n<pre><code>wp_link_pages( array( 'pagelink' => '#custom_title#' ) );\n</code></pre>\n\n<p>Then add our filter in <code>functions.php</code>. In callback function make an array of titles then check for the current page number and replace <code>#custom_title#</code> with value corresponding to current page number.</p>\n\n<p>Example:-</p>\n\n<pre><code>add_filter('wp_link_pages_link', 'wp_link_pages_link_custom_title', 10, 2);\n/**\n * Replace placeholder with custom titles\n * @param string $link Page link HTML\n * @param int $i Current page number\n * @return string $link Page link HTML\n */\nfunction wp_link_pages_link_custom_title($link, $i) {\n\n //Define array of custom titles\n $custom_titles = array(\n __('Custom title A', 'text-domain'),\n __('Custom title B', 'text-domain'),\n __('Custom title C', 'text-domain'),\n );\n\n //Default title when title is not set in array\n $default_title = __('Page', 'text-domain') . ' ' . $i; \n\n $i--; //Decrease the value by 1 because our array start with 0\n\n if (isset($custom_titles[$i])) { //Check if title exist in array if yes then replace it\n $link = str_replace('#custom_title#', $custom_titles[$i], $link);\n } else { //Replace with default title\n $link = str_replace('#custom_title#', $default_title, $link);\n }\n\n return $link;\n}\n</code></pre>\n"
},
{
"answer_id": 227022,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a way to support pagination titles of the form:</p>\n\n<pre><code><!--nextpage(.*?)?--> \n</code></pre>\n\n<p>in a simlar way as the core supports <code><!--more(.*?)?--></code>. </p>\n\n<p>Here's an example:</p>\n\n<pre><code><!--nextpage Planets -->\nLet's talk about the Planets\n<!--nextpage Mercury -->\nExotic Mercury\n<!--nextpage Venus-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>with the output similar to:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lAGwM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lAGwM.jpg\" alt=\"Pagination titles\"></a></p>\n\n<p>This was tested on the <em>Twenty Sixteen</em> theme, where I had to adjust the <em>padding</em> and <em>width</em> a little bit:</p>\n\n<pre><code>.page-links a, .page-links > span {\n width: auto;\n padding: 0 5px;\n}\n</code></pre>\n\n<h2>Demo plugin</h2>\n\n<p>Here's a demo plugin that uses the <code>content_pagination</code>, <code>wp_link_pages_link</code>, <code>pre_handle_404</code> and <code>wp_link_pages_args</code> filters to support this extenstion of the <em>nextpage</em> marker (<em>PHP 5.4+</em>):</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Content Pagination Titles\n * Description: Support for &lt;!--nextpage(.*?)?--&gt; in the post content\n * Version: 1.0.1\n * Plugin URI: http://wordpress.stackexchange.com/a/227022/26350\n */\n\nnamespace WPSE\\Question202709;\n\nadd_action( 'init', function()\n{\n $main = new Main;\n $main->init();\n} );\n\nclass Main\n{\n private $pagination_titles;\n\n public function init()\n {\n add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ], 10, 2 );\n add_filter( 'content_pagination', [ $this, 'content_pagination' ], -1, 2 );\n add_filter( 'wp_link_pages_link', [ $this, 'wp_link_pages_link' ], 10, 2 );\n add_filter( 'wp_link_pages_args', [ $this, 'wp_link_pages_args' ], PHP_INT_MAX );\n }\n\n public function content_pagination( $pages, $post )\n {\n // Empty content pagination titles for each run\n $this->pagination_titles = [];\n\n // Nothing to do if the post content doesn't contain pagination titles\n if( false === stripos( $post->post_content, '<!--nextpage' ) )\n return $pages;\n\n // Collect pagination titles\n preg_match_all( '/<!--nextpage(.*?)?-->/i', $post->post_content, $matches );\n if( isset( $matches[1] ) )\n $this->pagination_titles = $matches[1]; \n\n // Override $pages according to our new extended nextpage support\n $pages = preg_split( '/<!--nextpage(.*?)?-->/i', $post->post_content );\n\n // nextpage marker at the top\n if( isset( $pages[0] ) && '' == trim( $pages[0] ) )\n {\n // remove the empty page\n array_shift( $pages );\n } \n // nextpage marker not at the top\n else\n {\n // add the first numeric pagination title \n array_unshift( $this->pagination_titles, '1' );\n } \n return $pages;\n }\n\n public function wp_link_pages_link( $link, $i )\n {\n if( ! empty( $this->pagination_titles ) )\n {\n $from = '{{TITLE}}';\n $to = ! empty( $this->pagination_titles[$i-1] ) ? $this->pagination_titles[$i-1] : $i;\n $link = str_replace( $from, $to, $link );\n }\n\n return $link;\n }\n\n public function wp_link_pages_args( $params )\n { \n if( ! empty( $this->pagination_titles ) )\n {\n $params['next_or_number'] = 'number';\n $params['pagelink'] = str_replace( '%', '{{TITLE}}', $params['pagelink'] );\n }\n return $params;\n }\n\n /**\n * Based on the nextpage check in WP::handle_404()\n */\n public function pre_handle_404( $bool, \\WP_Query $q )\n {\n global $wp;\n\n if( $q->posts && is_singular() )\n {\n if ( $q->post instanceof \\WP_Post ) \n $p = clone $q->post;\n\n // check for paged content that exceeds the max number of pages\n $next = '<!--nextpage';\n if ( $p \n && false !== stripos( $p->post_content, $next ) \n && ! empty( $wp->query_vars['page'] ) \n ) {\n $page = trim( $wp->query_vars['page'], '/' );\n $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );\n\n if ( $success )\n {\n status_header( 200 );\n $bool = true;\n }\n }\n }\n return $bool;\n }\n\n} // end class\n</code></pre>\n\n<p><em>Installation</em>: Create the <code>/wp-content/plugins/content-pagination-titles/content-pagination-titles.php</code> file and activate the plugin. Always a good idea to backup before testing any plugin.</p>\n\n<p>If the top <em>nextpage</em> marker is missing, then the first pagination title is numeric.</p>\n\n<p>Also if a content pagination title is missing, i.e. <code><!--nextpage--></code>, then it will be numeric, just as expected.</p>\n\n<p>I first forgot about the <em>nextpage</em> bug in the <code>WP</code> class, that shows up if we modify the number of pages via the <code>content_pagination</code> filter. This was recently reported by @PieterGoosen here in <a href=\"https://core.trac.wordpress.org/ticket/35562\" rel=\"nofollow noreferrer\">#35562</a>. </p>\n\n<p>We try to overcome that in our demo plugin with a <code>pre_handle_404</code> filter callback, based on the <code>WP</code> class check <a href=\"https://github.com/WordPress/WordPress/blob/0016e4bb122a8da9b70d2703f805ba5a9821eadd/wp-includes/class-wp.php#L652-680\" rel=\"nofollow noreferrer\">here</a>, where we check for <code><!--nextpage</code> instead of <code><!--nextpage--></code>.</p>\n\n<h2>Tests</h2>\n\n<p>Here are some further tests:</p>\n\n<p><strong>Test #1</strong></p>\n\n<pre><code><!--nextpage-->\nLet's talk about the Planets\n<!--nextpage-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage-->\nOur Blue Earth\n<!--nextpage-->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>1</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9QbDd.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9QbDd.jpg\" alt=\"test1\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #2</strong></p>\n\n<pre><code>Let's talk about the Planets\n<!--nextpage-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage-->\nOur Blue Earth\n<!--nextpage-->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>5</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rH9Yq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rH9Yq.jpg\" alt=\"test2\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #3</strong></p>\n\n<pre><code><!--nextpage-->\nLet's talk about the Planets\n<!--nextpage Mercury-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>3</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/k6CTp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k6CTp.jpg\" alt=\"test3\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #4</strong></p>\n\n<pre><code>Let's talk about the Planets\n<!--nextpage Mercury-->\nExotic Mercury\n<!--nextpage Venus-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>Output with <em>Earth</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aZDHs.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aZDHs.jpg\" alt=\"test4\"></a></p>\n\n<p>as expected.</p>\n\n<h2>Alternatives</h2>\n\n<p>Another way would be to modify it to support pagination titles to be added with:</p>\n\n<pre><code><!--pt Earth-->\n</code></pre>\n\n<p>It might also be handy to support a single comment for all pagination titles (<em>pts</em>):</p>\n\n<pre><code><!--pts Planets|Mercury|Venus|Earth|Mars -->\n</code></pre>\n\n<p>or perhaps via custom fields?</p>\n"
}
] |
2015/09/15
|
[
"https://wordpress.stackexchange.com/questions/202709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17971/"
] |
I have split my post content into mutiple pages using the `<! - nextpage ->` code. I want to give my paginated links their own title instead of the regular 1,2,3. How can I do this? cause on this doc <https://codex.wordpress.org/Styling_Page-Links> it only mentions method to adding suffix or prefix. I just want to give each paged number their own custom title
|
Here's a way to support pagination titles of the form:
```
<!--nextpage(.*?)?-->
```
in a simlar way as the core supports `<!--more(.*?)?-->`.
Here's an example:
```
<!--nextpage Planets -->
Let's talk about the Planets
<!--nextpage Mercury -->
Exotic Mercury
<!--nextpage Venus-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
with the output similar to:
[](https://i.stack.imgur.com/lAGwM.jpg)
This was tested on the *Twenty Sixteen* theme, where I had to adjust the *padding* and *width* a little bit:
```
.page-links a, .page-links > span {
width: auto;
padding: 0 5px;
}
```
Demo plugin
-----------
Here's a demo plugin that uses the `content_pagination`, `wp_link_pages_link`, `pre_handle_404` and `wp_link_pages_args` filters to support this extenstion of the *nextpage* marker (*PHP 5.4+*):
```
<?php
/**
* Plugin Name: Content Pagination Titles
* Description: Support for <!--nextpage(.*?)?--> in the post content
* Version: 1.0.1
* Plugin URI: http://wordpress.stackexchange.com/a/227022/26350
*/
namespace WPSE\Question202709;
add_action( 'init', function()
{
$main = new Main;
$main->init();
} );
class Main
{
private $pagination_titles;
public function init()
{
add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ], 10, 2 );
add_filter( 'content_pagination', [ $this, 'content_pagination' ], -1, 2 );
add_filter( 'wp_link_pages_link', [ $this, 'wp_link_pages_link' ], 10, 2 );
add_filter( 'wp_link_pages_args', [ $this, 'wp_link_pages_args' ], PHP_INT_MAX );
}
public function content_pagination( $pages, $post )
{
// Empty content pagination titles for each run
$this->pagination_titles = [];
// Nothing to do if the post content doesn't contain pagination titles
if( false === stripos( $post->post_content, '<!--nextpage' ) )
return $pages;
// Collect pagination titles
preg_match_all( '/<!--nextpage(.*?)?-->/i', $post->post_content, $matches );
if( isset( $matches[1] ) )
$this->pagination_titles = $matches[1];
// Override $pages according to our new extended nextpage support
$pages = preg_split( '/<!--nextpage(.*?)?-->/i', $post->post_content );
// nextpage marker at the top
if( isset( $pages[0] ) && '' == trim( $pages[0] ) )
{
// remove the empty page
array_shift( $pages );
}
// nextpage marker not at the top
else
{
// add the first numeric pagination title
array_unshift( $this->pagination_titles, '1' );
}
return $pages;
}
public function wp_link_pages_link( $link, $i )
{
if( ! empty( $this->pagination_titles ) )
{
$from = '{{TITLE}}';
$to = ! empty( $this->pagination_titles[$i-1] ) ? $this->pagination_titles[$i-1] : $i;
$link = str_replace( $from, $to, $link );
}
return $link;
}
public function wp_link_pages_args( $params )
{
if( ! empty( $this->pagination_titles ) )
{
$params['next_or_number'] = 'number';
$params['pagelink'] = str_replace( '%', '{{TITLE}}', $params['pagelink'] );
}
return $params;
}
/**
* Based on the nextpage check in WP::handle_404()
*/
public function pre_handle_404( $bool, \WP_Query $q )
{
global $wp;
if( $q->posts && is_singular() )
{
if ( $q->post instanceof \WP_Post )
$p = clone $q->post;
// check for paged content that exceeds the max number of pages
$next = '<!--nextpage';
if ( $p
&& false !== stripos( $p->post_content, $next )
&& ! empty( $wp->query_vars['page'] )
) {
$page = trim( $wp->query_vars['page'], '/' );
$success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
if ( $success )
{
status_header( 200 );
$bool = true;
}
}
}
return $bool;
}
} // end class
```
*Installation*: Create the `/wp-content/plugins/content-pagination-titles/content-pagination-titles.php` file and activate the plugin. Always a good idea to backup before testing any plugin.
If the top *nextpage* marker is missing, then the first pagination title is numeric.
Also if a content pagination title is missing, i.e. `<!--nextpage-->`, then it will be numeric, just as expected.
I first forgot about the *nextpage* bug in the `WP` class, that shows up if we modify the number of pages via the `content_pagination` filter. This was recently reported by @PieterGoosen here in [#35562](https://core.trac.wordpress.org/ticket/35562).
We try to overcome that in our demo plugin with a `pre_handle_404` filter callback, based on the `WP` class check [here](https://github.com/WordPress/WordPress/blob/0016e4bb122a8da9b70d2703f805ba5a9821eadd/wp-includes/class-wp.php#L652-680), where we check for `<!--nextpage` instead of `<!--nextpage-->`.
Tests
-----
Here are some further tests:
**Test #1**
```
<!--nextpage-->
Let's talk about the Planets
<!--nextpage-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage-->
Our Blue Earth
<!--nextpage-->
The Red Planet
```
Output for *1* selected:
[](https://i.stack.imgur.com/9QbDd.jpg)
as expected.
**Test #2**
```
Let's talk about the Planets
<!--nextpage-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage-->
Our Blue Earth
<!--nextpage-->
The Red Planet
```
Output for *5* selected:
[](https://i.stack.imgur.com/rH9Yq.jpg)
as expected.
**Test #3**
```
<!--nextpage-->
Let's talk about the Planets
<!--nextpage Mercury-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
Output for *3* selected:
[](https://i.stack.imgur.com/k6CTp.jpg)
as expected.
**Test #4**
```
Let's talk about the Planets
<!--nextpage Mercury-->
Exotic Mercury
<!--nextpage Venus-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
Output with *Earth* selected:
[](https://i.stack.imgur.com/aZDHs.jpg)
as expected.
Alternatives
------------
Another way would be to modify it to support pagination titles to be added with:
```
<!--pt Earth-->
```
It might also be handy to support a single comment for all pagination titles (*pts*):
```
<!--pts Planets|Mercury|Venus|Earth|Mars -->
```
or perhaps via custom fields?
|
202,723 |
<p>I have created a small custom plugin which is just an HTML form. The HTML form is <code>echo</code>'d out using PHP and it includes a small JavaScript function that I want to run on submission. I cannot get it to work, however, and I am not sure what I am doing wrong. Is it not allowed to use JavaScript in this way? If not, what is the proper way to do it?</p>
<p>Running the below snippet does nothing when hitting the submit button.</p>
<pre><code>echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" value=\"Submit me\" /><br>
</form>
";
</code></pre>
<p><strong>Update:</strong></p>
<p>Here is the entire plugin, stripped down to just a small test. The JavaScript console shows nothing except a jQuery warning: <em>JQMIGRATE: jQuery.fn.live() is deprecated</em>. I am not sure where this originates from, but I do not use jQuery directly.</p>
<p>When I activate the plugin and click the button, the page is reloaded with the button and all, but the message <em>Yes, it was posted!</em> is not displayed. Thus it seems that no POST request is made. Removing the script and the <code>onsubmit</code> from the PHP <code>echo</code> produces the same behavior.</p>
<pre><code><?php
/*
Plugin Name: Test Plugin
*/
// Create plugin menu.
add_action('admin_menu', 'create_test_plugin_menu');
function create_test_plugin_menu()
{
add_menu_page('The Test Plugin', 'Test Plugin', 'administrator', __FILE__, 'setup_test_plugin');
}
function setup_test_plugin()
{
$submit_name = 'test_button';
if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST[$submit_name]) )
{
echo "Yes, it was posted!";
}
else
{
echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" name=\"{$submit_name}\" value=\"Submit me\" /><br>
</form>
";
}
}
?>
</code></pre>
<p>Here is what is printed to the HTML source, copied from the JavaScript console.</p>
<pre><code><script type="text/javascript">
function validateForm()
{
alert("FOOO");
return false;
}
</script>
<h1>Header</h1><br>
<form method="post" onsubmit="validateForm()">
<input type="submit" name="test_button" value="Submit me" /><br>
</form>
</code></pre>
|
[
{
"answer_id": 227012,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 3,
"selected": false,
"text": "<p>You can use filter <a href=\"https://developer.wordpress.org/reference/hooks/wp_link_pages_link/\"><code>wp_link_pages_link</code></a></p>\n\n<p>First pass our custom string placeholder (This can be anything you like except string containing <code>%</code>, just for now I am using <code>#custom_title#</code>).</p>\n\n<pre><code>wp_link_pages( array( 'pagelink' => '#custom_title#' ) );\n</code></pre>\n\n<p>Then add our filter in <code>functions.php</code>. In callback function make an array of titles then check for the current page number and replace <code>#custom_title#</code> with value corresponding to current page number.</p>\n\n<p>Example:-</p>\n\n<pre><code>add_filter('wp_link_pages_link', 'wp_link_pages_link_custom_title', 10, 2);\n/**\n * Replace placeholder with custom titles\n * @param string $link Page link HTML\n * @param int $i Current page number\n * @return string $link Page link HTML\n */\nfunction wp_link_pages_link_custom_title($link, $i) {\n\n //Define array of custom titles\n $custom_titles = array(\n __('Custom title A', 'text-domain'),\n __('Custom title B', 'text-domain'),\n __('Custom title C', 'text-domain'),\n );\n\n //Default title when title is not set in array\n $default_title = __('Page', 'text-domain') . ' ' . $i; \n\n $i--; //Decrease the value by 1 because our array start with 0\n\n if (isset($custom_titles[$i])) { //Check if title exist in array if yes then replace it\n $link = str_replace('#custom_title#', $custom_titles[$i], $link);\n } else { //Replace with default title\n $link = str_replace('#custom_title#', $default_title, $link);\n }\n\n return $link;\n}\n</code></pre>\n"
},
{
"answer_id": 227022,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a way to support pagination titles of the form:</p>\n\n<pre><code><!--nextpage(.*?)?--> \n</code></pre>\n\n<p>in a simlar way as the core supports <code><!--more(.*?)?--></code>. </p>\n\n<p>Here's an example:</p>\n\n<pre><code><!--nextpage Planets -->\nLet's talk about the Planets\n<!--nextpage Mercury -->\nExotic Mercury\n<!--nextpage Venus-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>with the output similar to:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lAGwM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lAGwM.jpg\" alt=\"Pagination titles\"></a></p>\n\n<p>This was tested on the <em>Twenty Sixteen</em> theme, where I had to adjust the <em>padding</em> and <em>width</em> a little bit:</p>\n\n<pre><code>.page-links a, .page-links > span {\n width: auto;\n padding: 0 5px;\n}\n</code></pre>\n\n<h2>Demo plugin</h2>\n\n<p>Here's a demo plugin that uses the <code>content_pagination</code>, <code>wp_link_pages_link</code>, <code>pre_handle_404</code> and <code>wp_link_pages_args</code> filters to support this extenstion of the <em>nextpage</em> marker (<em>PHP 5.4+</em>):</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Content Pagination Titles\n * Description: Support for &lt;!--nextpage(.*?)?--&gt; in the post content\n * Version: 1.0.1\n * Plugin URI: http://wordpress.stackexchange.com/a/227022/26350\n */\n\nnamespace WPSE\\Question202709;\n\nadd_action( 'init', function()\n{\n $main = new Main;\n $main->init();\n} );\n\nclass Main\n{\n private $pagination_titles;\n\n public function init()\n {\n add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ], 10, 2 );\n add_filter( 'content_pagination', [ $this, 'content_pagination' ], -1, 2 );\n add_filter( 'wp_link_pages_link', [ $this, 'wp_link_pages_link' ], 10, 2 );\n add_filter( 'wp_link_pages_args', [ $this, 'wp_link_pages_args' ], PHP_INT_MAX );\n }\n\n public function content_pagination( $pages, $post )\n {\n // Empty content pagination titles for each run\n $this->pagination_titles = [];\n\n // Nothing to do if the post content doesn't contain pagination titles\n if( false === stripos( $post->post_content, '<!--nextpage' ) )\n return $pages;\n\n // Collect pagination titles\n preg_match_all( '/<!--nextpage(.*?)?-->/i', $post->post_content, $matches );\n if( isset( $matches[1] ) )\n $this->pagination_titles = $matches[1]; \n\n // Override $pages according to our new extended nextpage support\n $pages = preg_split( '/<!--nextpage(.*?)?-->/i', $post->post_content );\n\n // nextpage marker at the top\n if( isset( $pages[0] ) && '' == trim( $pages[0] ) )\n {\n // remove the empty page\n array_shift( $pages );\n } \n // nextpage marker not at the top\n else\n {\n // add the first numeric pagination title \n array_unshift( $this->pagination_titles, '1' );\n } \n return $pages;\n }\n\n public function wp_link_pages_link( $link, $i )\n {\n if( ! empty( $this->pagination_titles ) )\n {\n $from = '{{TITLE}}';\n $to = ! empty( $this->pagination_titles[$i-1] ) ? $this->pagination_titles[$i-1] : $i;\n $link = str_replace( $from, $to, $link );\n }\n\n return $link;\n }\n\n public function wp_link_pages_args( $params )\n { \n if( ! empty( $this->pagination_titles ) )\n {\n $params['next_or_number'] = 'number';\n $params['pagelink'] = str_replace( '%', '{{TITLE}}', $params['pagelink'] );\n }\n return $params;\n }\n\n /**\n * Based on the nextpage check in WP::handle_404()\n */\n public function pre_handle_404( $bool, \\WP_Query $q )\n {\n global $wp;\n\n if( $q->posts && is_singular() )\n {\n if ( $q->post instanceof \\WP_Post ) \n $p = clone $q->post;\n\n // check for paged content that exceeds the max number of pages\n $next = '<!--nextpage';\n if ( $p \n && false !== stripos( $p->post_content, $next ) \n && ! empty( $wp->query_vars['page'] ) \n ) {\n $page = trim( $wp->query_vars['page'], '/' );\n $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );\n\n if ( $success )\n {\n status_header( 200 );\n $bool = true;\n }\n }\n }\n return $bool;\n }\n\n} // end class\n</code></pre>\n\n<p><em>Installation</em>: Create the <code>/wp-content/plugins/content-pagination-titles/content-pagination-titles.php</code> file and activate the plugin. Always a good idea to backup before testing any plugin.</p>\n\n<p>If the top <em>nextpage</em> marker is missing, then the first pagination title is numeric.</p>\n\n<p>Also if a content pagination title is missing, i.e. <code><!--nextpage--></code>, then it will be numeric, just as expected.</p>\n\n<p>I first forgot about the <em>nextpage</em> bug in the <code>WP</code> class, that shows up if we modify the number of pages via the <code>content_pagination</code> filter. This was recently reported by @PieterGoosen here in <a href=\"https://core.trac.wordpress.org/ticket/35562\" rel=\"nofollow noreferrer\">#35562</a>. </p>\n\n<p>We try to overcome that in our demo plugin with a <code>pre_handle_404</code> filter callback, based on the <code>WP</code> class check <a href=\"https://github.com/WordPress/WordPress/blob/0016e4bb122a8da9b70d2703f805ba5a9821eadd/wp-includes/class-wp.php#L652-680\" rel=\"nofollow noreferrer\">here</a>, where we check for <code><!--nextpage</code> instead of <code><!--nextpage--></code>.</p>\n\n<h2>Tests</h2>\n\n<p>Here are some further tests:</p>\n\n<p><strong>Test #1</strong></p>\n\n<pre><code><!--nextpage-->\nLet's talk about the Planets\n<!--nextpage-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage-->\nOur Blue Earth\n<!--nextpage-->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>1</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9QbDd.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9QbDd.jpg\" alt=\"test1\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #2</strong></p>\n\n<pre><code>Let's talk about the Planets\n<!--nextpage-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage-->\nOur Blue Earth\n<!--nextpage-->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>5</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rH9Yq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rH9Yq.jpg\" alt=\"test2\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #3</strong></p>\n\n<pre><code><!--nextpage-->\nLet's talk about the Planets\n<!--nextpage Mercury-->\nExotic Mercury\n<!--nextpage-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>Output for <em>3</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/k6CTp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k6CTp.jpg\" alt=\"test3\"></a></p>\n\n<p>as expected.</p>\n\n<p><strong>Test #4</strong></p>\n\n<pre><code>Let's talk about the Planets\n<!--nextpage Mercury-->\nExotic Mercury\n<!--nextpage Venus-->\nBeautiful Venus\n<!--nextpage Earth -->\nOur Blue Earth\n<!--nextpage Mars -->\nThe Red Planet\n</code></pre>\n\n<p>Output with <em>Earth</em> selected:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aZDHs.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aZDHs.jpg\" alt=\"test4\"></a></p>\n\n<p>as expected.</p>\n\n<h2>Alternatives</h2>\n\n<p>Another way would be to modify it to support pagination titles to be added with:</p>\n\n<pre><code><!--pt Earth-->\n</code></pre>\n\n<p>It might also be handy to support a single comment for all pagination titles (<em>pts</em>):</p>\n\n<pre><code><!--pts Planets|Mercury|Venus|Earth|Mars -->\n</code></pre>\n\n<p>or perhaps via custom fields?</p>\n"
}
] |
2015/09/15
|
[
"https://wordpress.stackexchange.com/questions/202723",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66556/"
] |
I have created a small custom plugin which is just an HTML form. The HTML form is `echo`'d out using PHP and it includes a small JavaScript function that I want to run on submission. I cannot get it to work, however, and I am not sure what I am doing wrong. Is it not allowed to use JavaScript in this way? If not, what is the proper way to do it?
Running the below snippet does nothing when hitting the submit button.
```
echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" value=\"Submit me\" /><br>
</form>
";
```
**Update:**
Here is the entire plugin, stripped down to just a small test. The JavaScript console shows nothing except a jQuery warning: *JQMIGRATE: jQuery.fn.live() is deprecated*. I am not sure where this originates from, but I do not use jQuery directly.
When I activate the plugin and click the button, the page is reloaded with the button and all, but the message *Yes, it was posted!* is not displayed. Thus it seems that no POST request is made. Removing the script and the `onsubmit` from the PHP `echo` produces the same behavior.
```
<?php
/*
Plugin Name: Test Plugin
*/
// Create plugin menu.
add_action('admin_menu', 'create_test_plugin_menu');
function create_test_plugin_menu()
{
add_menu_page('The Test Plugin', 'Test Plugin', 'administrator', __FILE__, 'setup_test_plugin');
}
function setup_test_plugin()
{
$submit_name = 'test_button';
if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST[$submit_name]) )
{
echo "Yes, it was posted!";
}
else
{
echo "
<script type=\"text/javascript\">
function validateForm()
{
alert(\"FOOO\");
return false;
}
</script>
<h1>Header</h1><br>
<form method=\"post\" onsubmit=\"validateForm()\">
<input type=\"submit\" name=\"{$submit_name}\" value=\"Submit me\" /><br>
</form>
";
}
}
?>
```
Here is what is printed to the HTML source, copied from the JavaScript console.
```
<script type="text/javascript">
function validateForm()
{
alert("FOOO");
return false;
}
</script>
<h1>Header</h1><br>
<form method="post" onsubmit="validateForm()">
<input type="submit" name="test_button" value="Submit me" /><br>
</form>
```
|
Here's a way to support pagination titles of the form:
```
<!--nextpage(.*?)?-->
```
in a simlar way as the core supports `<!--more(.*?)?-->`.
Here's an example:
```
<!--nextpage Planets -->
Let's talk about the Planets
<!--nextpage Mercury -->
Exotic Mercury
<!--nextpage Venus-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
with the output similar to:
[](https://i.stack.imgur.com/lAGwM.jpg)
This was tested on the *Twenty Sixteen* theme, where I had to adjust the *padding* and *width* a little bit:
```
.page-links a, .page-links > span {
width: auto;
padding: 0 5px;
}
```
Demo plugin
-----------
Here's a demo plugin that uses the `content_pagination`, `wp_link_pages_link`, `pre_handle_404` and `wp_link_pages_args` filters to support this extenstion of the *nextpage* marker (*PHP 5.4+*):
```
<?php
/**
* Plugin Name: Content Pagination Titles
* Description: Support for <!--nextpage(.*?)?--> in the post content
* Version: 1.0.1
* Plugin URI: http://wordpress.stackexchange.com/a/227022/26350
*/
namespace WPSE\Question202709;
add_action( 'init', function()
{
$main = new Main;
$main->init();
} );
class Main
{
private $pagination_titles;
public function init()
{
add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ], 10, 2 );
add_filter( 'content_pagination', [ $this, 'content_pagination' ], -1, 2 );
add_filter( 'wp_link_pages_link', [ $this, 'wp_link_pages_link' ], 10, 2 );
add_filter( 'wp_link_pages_args', [ $this, 'wp_link_pages_args' ], PHP_INT_MAX );
}
public function content_pagination( $pages, $post )
{
// Empty content pagination titles for each run
$this->pagination_titles = [];
// Nothing to do if the post content doesn't contain pagination titles
if( false === stripos( $post->post_content, '<!--nextpage' ) )
return $pages;
// Collect pagination titles
preg_match_all( '/<!--nextpage(.*?)?-->/i', $post->post_content, $matches );
if( isset( $matches[1] ) )
$this->pagination_titles = $matches[1];
// Override $pages according to our new extended nextpage support
$pages = preg_split( '/<!--nextpage(.*?)?-->/i', $post->post_content );
// nextpage marker at the top
if( isset( $pages[0] ) && '' == trim( $pages[0] ) )
{
// remove the empty page
array_shift( $pages );
}
// nextpage marker not at the top
else
{
// add the first numeric pagination title
array_unshift( $this->pagination_titles, '1' );
}
return $pages;
}
public function wp_link_pages_link( $link, $i )
{
if( ! empty( $this->pagination_titles ) )
{
$from = '{{TITLE}}';
$to = ! empty( $this->pagination_titles[$i-1] ) ? $this->pagination_titles[$i-1] : $i;
$link = str_replace( $from, $to, $link );
}
return $link;
}
public function wp_link_pages_args( $params )
{
if( ! empty( $this->pagination_titles ) )
{
$params['next_or_number'] = 'number';
$params['pagelink'] = str_replace( '%', '{{TITLE}}', $params['pagelink'] );
}
return $params;
}
/**
* Based on the nextpage check in WP::handle_404()
*/
public function pre_handle_404( $bool, \WP_Query $q )
{
global $wp;
if( $q->posts && is_singular() )
{
if ( $q->post instanceof \WP_Post )
$p = clone $q->post;
// check for paged content that exceeds the max number of pages
$next = '<!--nextpage';
if ( $p
&& false !== stripos( $p->post_content, $next )
&& ! empty( $wp->query_vars['page'] )
) {
$page = trim( $wp->query_vars['page'], '/' );
$success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
if ( $success )
{
status_header( 200 );
$bool = true;
}
}
}
return $bool;
}
} // end class
```
*Installation*: Create the `/wp-content/plugins/content-pagination-titles/content-pagination-titles.php` file and activate the plugin. Always a good idea to backup before testing any plugin.
If the top *nextpage* marker is missing, then the first pagination title is numeric.
Also if a content pagination title is missing, i.e. `<!--nextpage-->`, then it will be numeric, just as expected.
I first forgot about the *nextpage* bug in the `WP` class, that shows up if we modify the number of pages via the `content_pagination` filter. This was recently reported by @PieterGoosen here in [#35562](https://core.trac.wordpress.org/ticket/35562).
We try to overcome that in our demo plugin with a `pre_handle_404` filter callback, based on the `WP` class check [here](https://github.com/WordPress/WordPress/blob/0016e4bb122a8da9b70d2703f805ba5a9821eadd/wp-includes/class-wp.php#L652-680), where we check for `<!--nextpage` instead of `<!--nextpage-->`.
Tests
-----
Here are some further tests:
**Test #1**
```
<!--nextpage-->
Let's talk about the Planets
<!--nextpage-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage-->
Our Blue Earth
<!--nextpage-->
The Red Planet
```
Output for *1* selected:
[](https://i.stack.imgur.com/9QbDd.jpg)
as expected.
**Test #2**
```
Let's talk about the Planets
<!--nextpage-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage-->
Our Blue Earth
<!--nextpage-->
The Red Planet
```
Output for *5* selected:
[](https://i.stack.imgur.com/rH9Yq.jpg)
as expected.
**Test #3**
```
<!--nextpage-->
Let's talk about the Planets
<!--nextpage Mercury-->
Exotic Mercury
<!--nextpage-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
Output for *3* selected:
[](https://i.stack.imgur.com/k6CTp.jpg)
as expected.
**Test #4**
```
Let's talk about the Planets
<!--nextpage Mercury-->
Exotic Mercury
<!--nextpage Venus-->
Beautiful Venus
<!--nextpage Earth -->
Our Blue Earth
<!--nextpage Mars -->
The Red Planet
```
Output with *Earth* selected:
[](https://i.stack.imgur.com/aZDHs.jpg)
as expected.
Alternatives
------------
Another way would be to modify it to support pagination titles to be added with:
```
<!--pt Earth-->
```
It might also be handy to support a single comment for all pagination titles (*pts*):
```
<!--pts Planets|Mercury|Venus|Earth|Mars -->
```
or perhaps via custom fields?
|
202,742 |
<p>I am creating my custom Image slider,</p>
<p>in register_post_type() -> i use : supports = "title,thumbnail";</p>
<p>i use only two thing in supports, "title,thumbnail"</p>
<p>But post-thumbnails default position is Under Publish tab.</p>
<p>Its look ugly, I want to show feature image Under title fields.
Where editor show, i want to show my feature image on that position.</p>
<p>Kindly tell me how this possible?</p>
<pre><code>$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'textdomain' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'slider' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title','thumbnail')
);
register_post_type( 'slider', $args );
</code></pre>
<p><strong>IN case of not possible:</strong></p>
<p>If this not possible then tell me please:
when first time we open any post_type page, wordpress show 2 columns,
left side show title,editor,comments
or right side showing publish/thumbnail/category, etc</p>
<p>Is there any option to show default one column?
so all thing show in one side..</p>
|
[
{
"answer_id": 202743,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": -1,
"selected": false,
"text": "<p>You can simply drag the featured image under the Title field</p>\n"
},
{
"answer_id": 342721,
"author": "WorkshopforWeb",
"author_id": 157793,
"author_profile": "https://wordpress.stackexchange.com/users/157793",
"pm_score": 1,
"selected": false,
"text": "<p>Super late to the party, but well...</p>\n\n<p>If you want to show your featured image right under the Post title in your Admin area, use this piece of code in your functions.php :</p>\n\n<pre><code>add_action('do_meta_boxes', 'my_cpt_move_meta_box');\n\nfunction my_cpt_move_meta_box(){\n remove_meta_box( 'postimagediv', 'post_type', 'side' );\n add_meta_box('postimagediv', __('custom name'), 'post_thumbnail_meta_box', 'post_type', 'normal', 'high');\n}\n</code></pre>\n\n<p>Be sure to change <code>post_type</code> to you rcustom post type slug. Additionally, you can add a custom name for th eimage (instead of 'Featured Image')</p>\n"
}
] |
2015/09/15
|
[
"https://wordpress.stackexchange.com/questions/202742",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80320/"
] |
I am creating my custom Image slider,
in register\_post\_type() -> i use : supports = "title,thumbnail";
i use only two thing in supports, "title,thumbnail"
But post-thumbnails default position is Under Publish tab.
Its look ugly, I want to show feature image Under title fields.
Where editor show, i want to show my feature image on that position.
Kindly tell me how this possible?
```
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'textdomain' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'slider' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title','thumbnail')
);
register_post_type( 'slider', $args );
```
**IN case of not possible:**
If this not possible then tell me please:
when first time we open any post\_type page, wordpress show 2 columns,
left side show title,editor,comments
or right side showing publish/thumbnail/category, etc
Is there any option to show default one column?
so all thing show in one side..
|
Super late to the party, but well...
If you want to show your featured image right under the Post title in your Admin area, use this piece of code in your functions.php :
```
add_action('do_meta_boxes', 'my_cpt_move_meta_box');
function my_cpt_move_meta_box(){
remove_meta_box( 'postimagediv', 'post_type', 'side' );
add_meta_box('postimagediv', __('custom name'), 'post_thumbnail_meta_box', 'post_type', 'normal', 'high');
}
```
Be sure to change `post_type` to you rcustom post type slug. Additionally, you can add a custom name for th eimage (instead of 'Featured Image')
|
202,764 |
<p>I have a woocommerce setup for virtual products. All products are around 10MB and uploaded fine. I do however keep getting the following error show up when browsing the store:</p>
<pre><code>Trying to upload files larger than 128G is not allowed!
</code></pre>
<p>As you can see the file upload limit is 128GB and I have not tried uploading anything near the size of this. it was 128MB but i upped it to 128GB to try and get rid of the error.</p>
<p>Is there any reason why this could be happening?</p>
<p>Thanks
Ben</p>
|
[
{
"answer_id": 211118,
"author": "Jeff Campbell",
"author_id": 84919,
"author_profile": "https://wordpress.stackexchange.com/users/84919",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem and it turned out to be a bug with the Extra Product Options plugin. Was fixed by updating the plugin.</p>\n"
},
{
"answer_id": 242004,
"author": "Ajonetech",
"author_id": 104515,
"author_profile": "https://wordpress.stackexchange.com/users/104515",
"pm_score": 0,
"selected": false,
"text": "<p>This is PHP Memory Limit Error so you need to increase the Maximum Upload and PHP Memory Limit. Go in php.ini file and find and replace the code below.</p>\n\n<pre><code>upload_max_filesize = 1000M\npost_max_size = 2000M\nmemory_limit = 3000M\nfile_uploads = On\nmax_execution_time = 180\n</code></pre>\n\n<p>You can set your custom value 'M'Megabytes.</p>\n"
}
] |
2015/09/15
|
[
"https://wordpress.stackexchange.com/questions/202764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64567/"
] |
I have a woocommerce setup for virtual products. All products are around 10MB and uploaded fine. I do however keep getting the following error show up when browsing the store:
```
Trying to upload files larger than 128G is not allowed!
```
As you can see the file upload limit is 128GB and I have not tried uploading anything near the size of this. it was 128MB but i upped it to 128GB to try and get rid of the error.
Is there any reason why this could be happening?
Thanks
Ben
|
I had this problem and it turned out to be a bug with the Extra Product Options plugin. Was fixed by updating the plugin.
|
202,800 |
<p>I am trying to get a custom loop to work and I can not see why it is failing. </p>
<pre><code> $args = array( 'category_name' => 'audio', 'posts_per_page' => 6 );
$sound = new WP_Query( $args );
if( $sound->have_posts()):
while ( $sound->have_posts()) : $sound->the_post();
$file = get_attached_media('audio');
foreach( $file as $data) { ?>
<li><a href="#" data-src="<?php echo $data->guid; ?>" class="tracks" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?><?php the_title(); ?></a></li>
<?php } ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</code></pre>
<p>Right now there is one post in the category. I had 6 but only 5 showed up on the page. So I deleted them all and started over. I made one post. Nothing shows. When I do a var dump of the $file variable, I get this</p>
<pre><code> array(0){
}
</code></pre>
<p>shouldn't there be a "post" object there? is my loop messed up? </p>
|
[
{
"answer_id": 211118,
"author": "Jeff Campbell",
"author_id": 84919,
"author_profile": "https://wordpress.stackexchange.com/users/84919",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem and it turned out to be a bug with the Extra Product Options plugin. Was fixed by updating the plugin.</p>\n"
},
{
"answer_id": 242004,
"author": "Ajonetech",
"author_id": 104515,
"author_profile": "https://wordpress.stackexchange.com/users/104515",
"pm_score": 0,
"selected": false,
"text": "<p>This is PHP Memory Limit Error so you need to increase the Maximum Upload and PHP Memory Limit. Go in php.ini file and find and replace the code below.</p>\n\n<pre><code>upload_max_filesize = 1000M\npost_max_size = 2000M\nmemory_limit = 3000M\nfile_uploads = On\nmax_execution_time = 180\n</code></pre>\n\n<p>You can set your custom value 'M'Megabytes.</p>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14761/"
] |
I am trying to get a custom loop to work and I can not see why it is failing.
```
$args = array( 'category_name' => 'audio', 'posts_per_page' => 6 );
$sound = new WP_Query( $args );
if( $sound->have_posts()):
while ( $sound->have_posts()) : $sound->the_post();
$file = get_attached_media('audio');
foreach( $file as $data) { ?>
<li><a href="#" data-src="<?php echo $data->guid; ?>" class="tracks" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?><?php the_title(); ?></a></li>
<?php } ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
Right now there is one post in the category. I had 6 but only 5 showed up on the page. So I deleted them all and started over. I made one post. Nothing shows. When I do a var dump of the $file variable, I get this
```
array(0){
}
```
shouldn't there be a "post" object there? is my loop messed up?
|
I had this problem and it turned out to be a bug with the Extra Product Options plugin. Was fixed by updating the plugin.
|
202,828 |
<p>I have this query so far :</p>
<pre><code> $user_args = array(
'role' => 'frontend_vendor',
'orderby' => 'display_name',
'order' => 'ASC',
'number' => $no,
'offset' => $offset
);
$user_query = new WP_User_Query( $user_args );
</code></pre>
<p>Now what I want to do is to get all users that has only posts, i have an example query that i want to do. how do i do this with <code>wp_query()</code>?</p>
<pre><code>SELECT users.id, posts.id
FROM wp_users
RIGHT JOIN wp_posts
ON wp_users.id = wp_posts.user_id
WHERE wp_posts.post_type = 'downloads'
AND wp_users.role = 'frontend_vendor'
ORDER BY display_name
ASC
LIMT 8
OFFEST 0
</code></pre>
<p>If the user has no posts, he should not be selected. </p>
|
[
{
"answer_id": 202835,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 0,
"selected": false,
"text": "<p>Here are below some possible options:</p>\n\n<p><a href=\"http://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow noreferrer\">codex link</a></p>\n\n<p>Order & Orderby Parameters we can add post_count otherwise there is no such parameter such as \"posts_per_author\" does not exist in wp_query refrence</p>\n\n<p>please include orderby in your query </p>\n\n<pre><code>'orderby' => 'post_count'\n\nFROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) LEFT OUTER JOIN (\n SELECT post_author, COUNT(*) as post_count\n FROM wp_posts\n WHERE post_type = 'post' AND (post_status = 'publish' OR post_status = 'private')\n GROUP BY post_author\n ) p ON (wp_users.ID = p.post_author)\n</code></pre>\n\n<p>Use count in code according to requirement.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_list_authors\" rel=\"nofollow noreferrer\">Get Authors or users</a></p>\n\n<pre><code><?php $list = wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC&number=3'); ?>\n<?php echo\"<pre>\"; print_r($list); echo\"</pre>\"; ?>\n</code></pre>\n\n<p>\"optioncount\" can help in this case.</p>\n\n<p>with direct query please see this post:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/31722/get-users-with-atleast-one-post\">Get users with atleast one post</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 202916,
"author": "kenn",
"author_id": 80502,
"author_profile": "https://wordpress.stackexchange.com/users/80502",
"pm_score": 3,
"selected": true,
"text": "<p>add this in your arguments <code>'query_id' => 'authors_with_posts',</code></p>\n\n<pre><code> $user_args = array(\n 'role' => 'frontend_vendor',\n 'orderby' => 'display_name', \n 'query_id' => 'authors_with_posts',\n 'order' => 'ASC', \n 'number' => $no,\n 'offset' => $offset\n );\n</code></pre>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80451/"
] |
I have this query so far :
```
$user_args = array(
'role' => 'frontend_vendor',
'orderby' => 'display_name',
'order' => 'ASC',
'number' => $no,
'offset' => $offset
);
$user_query = new WP_User_Query( $user_args );
```
Now what I want to do is to get all users that has only posts, i have an example query that i want to do. how do i do this with `wp_query()`?
```
SELECT users.id, posts.id
FROM wp_users
RIGHT JOIN wp_posts
ON wp_users.id = wp_posts.user_id
WHERE wp_posts.post_type = 'downloads'
AND wp_users.role = 'frontend_vendor'
ORDER BY display_name
ASC
LIMT 8
OFFEST 0
```
If the user has no posts, he should not be selected.
|
add this in your arguments `'query_id' => 'authors_with_posts',`
```
$user_args = array(
'role' => 'frontend_vendor',
'orderby' => 'display_name',
'query_id' => 'authors_with_posts',
'order' => 'ASC',
'number' => $no,
'offset' => $offset
);
```
|
202,833 |
<p>Searching the code for related posts I found two almost identical code snippets, the only difference being that one uses echo: </p>
<pre><code>echo '<li><a href="' . get_permalink() . '" title="' . the_title_attribute() . '">' . the_title() . '</a></li>';
</code></pre>
<p>and the other does not:</p>
<pre><code><li>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>"> <h4><?php the_title() ?></h4></a>
</li>
</code></pre>
<p>Personally, I understand the second version (which mixes html with php) better, but I suspect, WP being what it is (always preferring php over html), that the first version may be the official way of doing things.</p>
<p>Is there are any preferred way of doing things in this case? And if yes why?</p>
|
[
{
"answer_id": 202836,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 2,
"selected": false,
"text": "<h3>First one</h3>\n\n<p>I don't know any preferred way on this, you can use both where which demands. Though the first one you mentioned contain bugs:</p>\n\n<pre><code>echo '<li><a href=\"' . get_permalink() . '\" title=\"' . the_title_attribute() . '\">' . the_title() . '</a></li>';\n</code></pre>\n\n<p><code>the_title_attribute()</code> doesn't return, but directly echo things. So when you are using it inside an <code>echo</code>, do it like so:</p>\n\n<pre><code>the_title_attribute( array( 'echo' => 0 ) )\n</code></pre>\n\n<p>similarly <code>the_title()</code> itself echo the whole, so when you are using it inside an <code>echo</code> use <code>get_the_title()</code> instead.</p>\n\n<p>So the first one while corrected would be:</p>\n\n<pre><code>echo '<li><a href=\"'. get_permalink() .'\" title=\"'. the_title_attribute( array( 'echo' => 0 ) ) .'\">'. get_the_title() .'</a></li>';\n</code></pre>\n\n<h3>Second one</h3>\n\n<p>Why a block element is inside an inline element?</p>\n\n<pre><code><li>\n <a href=\"<?php the_permalink() ?>\" title=\"<?php the_title_attribute() ?>\">\n <h4><?php the_title() ?></h4>\n </a>\n</li>\n</code></pre>\n\n<p>it shouldn't be that way, but something like this:</p>\n\n<pre><code><li>\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_title(); ?>\n </a>\n</li>\n</code></pre>\n"
},
{
"answer_id": 202840,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 4,
"selected": true,
"text": "<p>The main differences are: the first snippet has <em>html inside php</em> while the second one has <em>php inside html</em>. Both approaches are basically valid, both are fine.</p>\n\n<p>I would however always prefer (and recommend) to have <em>php inside html</em> because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it. </p>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
Searching the code for related posts I found two almost identical code snippets, the only difference being that one uses echo:
```
echo '<li><a href="' . get_permalink() . '" title="' . the_title_attribute() . '">' . the_title() . '</a></li>';
```
and the other does not:
```
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>"> <h4><?php the_title() ?></h4></a>
</li>
```
Personally, I understand the second version (which mixes html with php) better, but I suspect, WP being what it is (always preferring php over html), that the first version may be the official way of doing things.
Is there are any preferred way of doing things in this case? And if yes why?
|
The main differences are: the first snippet has *html inside php* while the second one has *php inside html*. Both approaches are basically valid, both are fine.
I would however always prefer (and recommend) to have *php inside html* because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it.
|
202,834 |
<p>Hi my code is below for adding shortcode in posts. when i am adding shortcode two times it shows me heading two times that i added in code "Recent Posts" is there is way to show this heading only top means one time?<a href="https://i.stack.imgur.com/RuFoO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RuFoO.png" alt="enter image description here"></a></p>
<pre><code>/*shortcode start*/
add_shortcode( 'recent-posts', 'PL_recent_posts' );
function PL_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
'order' => 'ASC',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' , 'colorss' => $color ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
</code></pre>
|
[
{
"answer_id": 202836,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 2,
"selected": false,
"text": "<h3>First one</h3>\n\n<p>I don't know any preferred way on this, you can use both where which demands. Though the first one you mentioned contain bugs:</p>\n\n<pre><code>echo '<li><a href=\"' . get_permalink() . '\" title=\"' . the_title_attribute() . '\">' . the_title() . '</a></li>';\n</code></pre>\n\n<p><code>the_title_attribute()</code> doesn't return, but directly echo things. So when you are using it inside an <code>echo</code>, do it like so:</p>\n\n<pre><code>the_title_attribute( array( 'echo' => 0 ) )\n</code></pre>\n\n<p>similarly <code>the_title()</code> itself echo the whole, so when you are using it inside an <code>echo</code> use <code>get_the_title()</code> instead.</p>\n\n<p>So the first one while corrected would be:</p>\n\n<pre><code>echo '<li><a href=\"'. get_permalink() .'\" title=\"'. the_title_attribute( array( 'echo' => 0 ) ) .'\">'. get_the_title() .'</a></li>';\n</code></pre>\n\n<h3>Second one</h3>\n\n<p>Why a block element is inside an inline element?</p>\n\n<pre><code><li>\n <a href=\"<?php the_permalink() ?>\" title=\"<?php the_title_attribute() ?>\">\n <h4><?php the_title() ?></h4>\n </a>\n</li>\n</code></pre>\n\n<p>it shouldn't be that way, but something like this:</p>\n\n<pre><code><li>\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php the_title(); ?>\n </a>\n</li>\n</code></pre>\n"
},
{
"answer_id": 202840,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 4,
"selected": true,
"text": "<p>The main differences are: the first snippet has <em>html inside php</em> while the second one has <em>php inside html</em>. Both approaches are basically valid, both are fine.</p>\n\n<p>I would however always prefer (and recommend) to have <em>php inside html</em> because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it. </p>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41012/"
] |
Hi my code is below for adding shortcode in posts. when i am adding shortcode two times it shows me heading two times that i added in code "Recent Posts" is there is way to show this heading only top means one time?[](https://i.stack.imgur.com/RuFoO.png)
```
/*shortcode start*/
add_shortcode( 'recent-posts', 'PL_recent_posts' );
function PL_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
'order' => 'ASC',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' , 'colorss' => $color ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
```
|
The main differences are: the first snippet has *html inside php* while the second one has *php inside html*. Both approaches are basically valid, both are fine.
I would however always prefer (and recommend) to have *php inside html* because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it.
|
202,859 |
<p>I've created two new Custom Post types using code that I've used successfully on other projects without issue. The first is called <code>top_charts</code>, the other <code>case_studies</code>, and both appear correctly in the admin menu and I can create new posts.</p>
<p>Unfortunately the new posts don't appear. I just get a <code>404.php</code> response.</p>
<p>I've created an <code>archive-top_charts.php</code> to see if I can get anything to appear, but I see a <code>404.php</code> "page not found" reply.</p>
<p>I originally named the custom posts <code>top-charts</code> and <code>case-studies</code>, but I thought the hyphen might have been the problem, and so renamed them to use an underscore instead. It hasn't helped.</p>
<p>I've tried re-saving my Permalinks, but nothing has changed. My .htaccess page looks like what you'd expect, too (and other pages works fine). What else can I check?</p>
|
[
{
"answer_id": 202861,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 6,
"selected": true,
"text": "<p>For fixing custom post not found please use below code in your <code>functions.php</code>:</p>\n<pre><code>flush_rewrite_rules( false );\n</code></pre>\n<p>You should only do this as a temporary measure otherwise it will run on every page load.</p>\n<p>For more details please follow <a href=\"https://web.archive.org/web/20140403185155/https://nooshu.com/page-not-found-with-custom-post-types\" rel=\"noreferrer\">this link</a></p>\n<p>As for the <code>archive-top_charts.php</code> not appearing, make sure you have <code>'has_archive' => true</code> when you're registering your post type.</p>\n"
},
{
"answer_id": 251591,
"author": "Danny",
"author_id": 110393,
"author_profile": "https://wordpress.stackexchange.com/users/110393",
"pm_score": 5,
"selected": false,
"text": "<p>You don't have to edit your php code!</p>\n\n<p>While you can do this in the function that registers your custom post type, like the other answers, you can also do this in the settings menu, thus avoiding touching your php code:</p>\n\n<p>To flush WordPress rewrite rules or permalinks (usually needs to be done manually for new custom post types) from the Dashboard:</p>\n\n<ol>\n<li>In the main menu find \"Settings > Permalinks\".</li>\n<li>Scroll down if needed and click \"Save Changes\".</li>\n<li>Rewrite rules and permalinks are flushed.</li>\n</ol>\n\n<p>It's that simple!</p>\n\n<p><a href=\"https://i.stack.imgur.com/Yp4Mg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Yp4Mg.png\" alt=\"image of saving permalinks page\"></a>\n<a href=\"https://typerocket.com/flushing-permalinks-in-wordpress/\" rel=\"noreferrer\">reference</a></p>\n"
},
{
"answer_id": 338709,
"author": "shaneonabike",
"author_id": 78099,
"author_profile": "https://wordpress.stackexchange.com/users/78099",
"pm_score": 0,
"selected": false,
"text": "<p>I realize that this is late in the game (and may not be the related problem), but I wanted to point out to others a possible issue.</p>\n\n<p>In my case, I had set my taxonomy rewrite to tools and the content type rewrite to the same thing. Therefore, it would never work properly as it was a conflict. Unfortunately, there is no detection for such a thing so I figured I would just point it out to others.</p>\n"
},
{
"answer_id": 355692,
"author": "David Salcer",
"author_id": 169650,
"author_profile": "https://wordpress.stackexchange.com/users/169650",
"pm_score": -1,
"selected": false,
"text": "<p>In my case it was missing rights in my development folder so .htaccess file could not have been created ad/or modified.</p>\n\n<p>So manual flushing or Saving changes in WP Permalinks was not helping.</p>\n\n<p>Solution was to create .htaccess file by myself </p>\n"
},
{
"answer_id": 379877,
"author": "Arman H",
"author_id": 134743,
"author_profile": "https://wordpress.stackexchange.com/users/134743",
"pm_score": 0,
"selected": false,
"text": "<p>I just added this line for rewrite rules this was the reason for me.\nafter comment or removed it solved but you can make it true also.</p>\n<pre><code>flush_rewrite_rules( true );\n</code></pre>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] |
I've created two new Custom Post types using code that I've used successfully on other projects without issue. The first is called `top_charts`, the other `case_studies`, and both appear correctly in the admin menu and I can create new posts.
Unfortunately the new posts don't appear. I just get a `404.php` response.
I've created an `archive-top_charts.php` to see if I can get anything to appear, but I see a `404.php` "page not found" reply.
I originally named the custom posts `top-charts` and `case-studies`, but I thought the hyphen might have been the problem, and so renamed them to use an underscore instead. It hasn't helped.
I've tried re-saving my Permalinks, but nothing has changed. My .htaccess page looks like what you'd expect, too (and other pages works fine). What else can I check?
|
For fixing custom post not found please use below code in your `functions.php`:
```
flush_rewrite_rules( false );
```
You should only do this as a temporary measure otherwise it will run on every page load.
For more details please follow [this link](https://web.archive.org/web/20140403185155/https://nooshu.com/page-not-found-with-custom-post-types)
As for the `archive-top_charts.php` not appearing, make sure you have `'has_archive' => true` when you're registering your post type.
|
202,860 |
<p>I'm currently writing a script that is running on a server and is supposed to get information about
a) the WordPress version
b) the plugins
c) the plugin versions.</p>
<p>The WordPress version number is no problem, but I'm not sure how to reliably obtain the required plugin information. I've located the plugin folder (wp-content/plugins). Does this folder contain all plugins?</p>
<p>Even if it does, I don't know if there is a fixed structure to get
a) the official name
b) the official version number
of all plugins. </p>
<p>For example, one plugin I checked had the version number in a .php file with an @version annotation, but the version of the second plugin I checked was just part of the comments (Version = 2.66 or something like this).</p>
<p>Is there a reliable way to obtain this information without using PHP (because the script I'm writing is not limited to WordPress and must run on servers without PHP)? Something like a common structure, or a central file with collected information on the plugins? </p>
|
[
{
"answer_id": 202861,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 6,
"selected": true,
"text": "<p>For fixing custom post not found please use below code in your <code>functions.php</code>:</p>\n<pre><code>flush_rewrite_rules( false );\n</code></pre>\n<p>You should only do this as a temporary measure otherwise it will run on every page load.</p>\n<p>For more details please follow <a href=\"https://web.archive.org/web/20140403185155/https://nooshu.com/page-not-found-with-custom-post-types\" rel=\"noreferrer\">this link</a></p>\n<p>As for the <code>archive-top_charts.php</code> not appearing, make sure you have <code>'has_archive' => true</code> when you're registering your post type.</p>\n"
},
{
"answer_id": 251591,
"author": "Danny",
"author_id": 110393,
"author_profile": "https://wordpress.stackexchange.com/users/110393",
"pm_score": 5,
"selected": false,
"text": "<p>You don't have to edit your php code!</p>\n\n<p>While you can do this in the function that registers your custom post type, like the other answers, you can also do this in the settings menu, thus avoiding touching your php code:</p>\n\n<p>To flush WordPress rewrite rules or permalinks (usually needs to be done manually for new custom post types) from the Dashboard:</p>\n\n<ol>\n<li>In the main menu find \"Settings > Permalinks\".</li>\n<li>Scroll down if needed and click \"Save Changes\".</li>\n<li>Rewrite rules and permalinks are flushed.</li>\n</ol>\n\n<p>It's that simple!</p>\n\n<p><a href=\"https://i.stack.imgur.com/Yp4Mg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Yp4Mg.png\" alt=\"image of saving permalinks page\"></a>\n<a href=\"https://typerocket.com/flushing-permalinks-in-wordpress/\" rel=\"noreferrer\">reference</a></p>\n"
},
{
"answer_id": 338709,
"author": "shaneonabike",
"author_id": 78099,
"author_profile": "https://wordpress.stackexchange.com/users/78099",
"pm_score": 0,
"selected": false,
"text": "<p>I realize that this is late in the game (and may not be the related problem), but I wanted to point out to others a possible issue.</p>\n\n<p>In my case, I had set my taxonomy rewrite to tools and the content type rewrite to the same thing. Therefore, it would never work properly as it was a conflict. Unfortunately, there is no detection for such a thing so I figured I would just point it out to others.</p>\n"
},
{
"answer_id": 355692,
"author": "David Salcer",
"author_id": 169650,
"author_profile": "https://wordpress.stackexchange.com/users/169650",
"pm_score": -1,
"selected": false,
"text": "<p>In my case it was missing rights in my development folder so .htaccess file could not have been created ad/or modified.</p>\n\n<p>So manual flushing or Saving changes in WP Permalinks was not helping.</p>\n\n<p>Solution was to create .htaccess file by myself </p>\n"
},
{
"answer_id": 379877,
"author": "Arman H",
"author_id": 134743,
"author_profile": "https://wordpress.stackexchange.com/users/134743",
"pm_score": 0,
"selected": false,
"text": "<p>I just added this line for rewrite rules this was the reason for me.\nafter comment or removed it solved but you can make it true also.</p>\n<pre><code>flush_rewrite_rules( true );\n</code></pre>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80462/"
] |
I'm currently writing a script that is running on a server and is supposed to get information about
a) the WordPress version
b) the plugins
c) the plugin versions.
The WordPress version number is no problem, but I'm not sure how to reliably obtain the required plugin information. I've located the plugin folder (wp-content/plugins). Does this folder contain all plugins?
Even if it does, I don't know if there is a fixed structure to get
a) the official name
b) the official version number
of all plugins.
For example, one plugin I checked had the version number in a .php file with an @version annotation, but the version of the second plugin I checked was just part of the comments (Version = 2.66 or something like this).
Is there a reliable way to obtain this information without using PHP (because the script I'm writing is not limited to WordPress and must run on servers without PHP)? Something like a common structure, or a central file with collected information on the plugins?
|
For fixing custom post not found please use below code in your `functions.php`:
```
flush_rewrite_rules( false );
```
You should only do this as a temporary measure otherwise it will run on every page load.
For more details please follow [this link](https://web.archive.org/web/20140403185155/https://nooshu.com/page-not-found-with-custom-post-types)
As for the `archive-top_charts.php` not appearing, make sure you have `'has_archive' => true` when you're registering your post type.
|
202,871 |
<p>Ajax call returns 0 as output. I am sure that hook is not working and it's not calling the <code>test2</code> method. Why is <code>add_action(...</code> not working inside class in <code>functions.php</code>?</p>
<p>--------Wrap inside <code>functions.php</code> Starts-------</p>
<pre><code>class test{
public function __construct() {
add_action( 'wp_ajax_test2', array( $this, 'test2' ) );
}
public function test1() { ?>
<script>
jQuery(document).ready(function($){
var ajaxurl = "<?php echo get_site_url();?>/wp-admin/admin-ajax.php";
var data = {'action':'test2'};
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(val) {
alert(val);
},
});
});
</script><?php
}
public function test2(){
echo "success";
exit;
}
}
</code></pre>
<p>--------Wrap inside <code>functions.php</code> Ends-------</p>
<p>Created an object in a template page and call to test1 method:</p>
<pre><code>$ob_call = new test;
$ob_call->test1();
</code></pre>
|
[
{
"answer_id": 202893,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 1,
"selected": false,
"text": "<p>While I am not sure why you want to do it like this, please find below the working code. Please note the comments in line. I hope this helps.</p>\n\n<pre><code>\nclass test{\n public function __construct() {\n add_action( 'wp_ajax_test2', array( $this, 'test2' ) );\n /* Front end ajax needs this. */\n add_action( 'wp_ajax_nopriv_test2', array( $this, 'test2' ) );\n add_action( 'wp_enqueue_scripts', array( $this, 'test1' ) );\n }\n\n public function test1() {\n /* in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value */\n wp_localize_script('test-script-ajax', 'ajaxobj', array('ajaxurl' => admin_url('admin-ajax.php')));\n /* Moved your js to a separate js file and enquing it the WordPress way */ \n wp_enqueue_script( 'test-script-ajax', get_stylesheet_directory_uri() . '/js/test-ajax.js', array( 'jquery' ));\n }\n\n public function test2(){\n echo \"success\";\n exit;\n }\n}\n\n$ob_call = new test;\n$ob_call->test1();\n\n</code></pre>\n\n<p>Here is the code in test-ajax.js file</p>\n\n<pre><code>\njQuery(document).ready(function($){\n var data = { 'action':'test2' };\n jQuery.post( ajaxobj.ajaxurl, data, function( response ) {\n alert(response);\n });\n});\n</code></pre>\n"
},
{
"answer_id": 203378,
"author": "fernandus",
"author_id": 80467,
"author_profile": "https://wordpress.stackexchange.com/users/80467",
"pm_score": 0,
"selected": false,
"text": "<p>It works now</p>\n<p>----------<strong>Function.php</strong>---------------</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wp_ajax_test2', array( 'test', 'test2' ) );\n\nclass test{\n\n public function __construct() {\n \n } \n public function test1() { ?>\n <script>\n jQuery(document).ready(function($){\n var ajaxurl = "<?php echo get_site_url();?>/wp-admin/admin-ajax.php";\n var data = {'action':'test2'};\n $.ajax({ \n url: ajaxurl,\n type: "POST",\n data: data,\n success: function(val) {\n alert(val);\n },\n }); \n }); \n </script><?php \n } \n public function test2(){\n echo "success";\n exit;\n } \n \n}\n</code></pre>\n<hr />\n<p>------------------page (<strong>Template</strong>)-------------</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ob_call = new test;\n\n$ob_call->test1();\n</code></pre>\n<p>Have a look to\n<a href=\"https://wordpress.stackexchange.com/questions/203383/why-hooking-differs-in-plugin-and-function-php-wordpress\">https://wordpress.stackexchange.com/questions/203383/why-hooking-differs-in-plugin-and-function-php-wordpress</a></p>\n"
},
{
"answer_id": 398994,
"author": "Ayoub Bousetta",
"author_id": 199543,
"author_profile": "https://wordpress.stackexchange.com/users/199543",
"pm_score": 0,
"selected": false,
"text": "<p>Add <code>wp_die();</code> at the end the your function.</p>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80467/"
] |
Ajax call returns 0 as output. I am sure that hook is not working and it's not calling the `test2` method. Why is `add_action(...` not working inside class in `functions.php`?
--------Wrap inside `functions.php` Starts-------
```
class test{
public function __construct() {
add_action( 'wp_ajax_test2', array( $this, 'test2' ) );
}
public function test1() { ?>
<script>
jQuery(document).ready(function($){
var ajaxurl = "<?php echo get_site_url();?>/wp-admin/admin-ajax.php";
var data = {'action':'test2'};
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(val) {
alert(val);
},
});
});
</script><?php
}
public function test2(){
echo "success";
exit;
}
}
```
--------Wrap inside `functions.php` Ends-------
Created an object in a template page and call to test1 method:
```
$ob_call = new test;
$ob_call->test1();
```
|
While I am not sure why you want to do it like this, please find below the working code. Please note the comments in line. I hope this helps.
```
class test{
public function __construct() {
add_action( 'wp_ajax_test2', array( $this, 'test2' ) );
/* Front end ajax needs this. */
add_action( 'wp_ajax_nopriv_test2', array( $this, 'test2' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'test1' ) );
}
public function test1() {
/* in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value */
wp_localize_script('test-script-ajax', 'ajaxobj', array('ajaxurl' => admin_url('admin-ajax.php')));
/* Moved your js to a separate js file and enquing it the WordPress way */
wp_enqueue_script( 'test-script-ajax', get_stylesheet_directory_uri() . '/js/test-ajax.js', array( 'jquery' ));
}
public function test2(){
echo "success";
exit;
}
}
$ob_call = new test;
$ob_call->test1();
```
Here is the code in test-ajax.js file
```
jQuery(document).ready(function($){
var data = { 'action':'test2' };
jQuery.post( ajaxobj.ajaxurl, data, function( response ) {
alert(response);
});
});
```
|
202,872 |
<p>I have a site that needs to migrate from WP E-Commerce to WooCommerce.</p>
<p>I'm trying to use <code>WP All Import Pro</code> + <code>WP All Import Woocommerce add on</code> to do this.</p>
<p>I exported the WP E-Commerce products in an XML file, and imported the XML file into WooCommerce products using WP All Import.</p>
<p>It works fine, except I can't get the image URL from the XML file, there is only a thumbnail ID, which can't be used by the WP All Import Woocommerce add on (that I can see).</p>
<p>So, <strong>I'd love to be able to convert a list of thumbnail IDs into their image URL equivalents</strong>, and then swap these these URLs into the thumbnail ID field in the XML file.</p>
<p>How do I do this? Help appreciated.</p>
|
[
{
"answer_id": 202878,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 2,
"selected": false,
"text": "<p>There are two functions you can use for this: <code>wp_get_attachment_url</code> to get the full sized image or <code>wp_get_attachment_thumb_url</code>, which gets the url of the thumbnail of that attachment. Either function takes the attachment id as the sole argument:</p>\n\n<pre><code>$attachment_id= 25;\n//Get the full url\n$url = wp_get_attachment_url( $attachment_id );\n//get the thumbnail\n$thumb = wp_get_attachment_thumb_url( $attachment_id );\n</code></pre>\n\n<p>Not sure how to get this done in your XML file, though, so this is a partial answer, but hopefully it sends you in the right direction.</p>\n"
},
{
"answer_id": 203397,
"author": "Ashok G",
"author_id": 44400,
"author_profile": "https://wordpress.stackexchange.com/users/44400",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this will probably solve your problem</p>\n\n<pre><code><?php if ( $post->post_type == 'data-design' && $post->post_status == 'publish' ) {\n $attachments = get_posts( array(\n 'post_type' => 'attachment',\n 'posts_per_page' => -1,\n 'post_parent' => $post->ID,\n 'exclude' => get_post_thumbnail_id()\n ) );\n\n if ( $attachments ) {\n foreach ( $attachments as $attachment ) {\n $class = \"post-attachment mime-\" . sanitize_title( $attachment->post_mime_type );\n $thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );\n echo '<li class=\"' . $class . ' data-design-thumbnail\">' . $thumbimg . '</li>';\n }\n\n }\n}\n?>\n</code></pre>\n\n<p>In the post type you could specify the required post type for which you need to fetch the images.</p>\n\n<p><a href=\"http://www.wpbeginner.com/wp-themes/how-to-get-all-post-attachments-in-wordpress-except-for-featured-image/\" rel=\"nofollow\">source</a></p>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] |
I have a site that needs to migrate from WP E-Commerce to WooCommerce.
I'm trying to use `WP All Import Pro` + `WP All Import Woocommerce add on` to do this.
I exported the WP E-Commerce products in an XML file, and imported the XML file into WooCommerce products using WP All Import.
It works fine, except I can't get the image URL from the XML file, there is only a thumbnail ID, which can't be used by the WP All Import Woocommerce add on (that I can see).
So, **I'd love to be able to convert a list of thumbnail IDs into their image URL equivalents**, and then swap these these URLs into the thumbnail ID field in the XML file.
How do I do this? Help appreciated.
|
There are two functions you can use for this: `wp_get_attachment_url` to get the full sized image or `wp_get_attachment_thumb_url`, which gets the url of the thumbnail of that attachment. Either function takes the attachment id as the sole argument:
```
$attachment_id= 25;
//Get the full url
$url = wp_get_attachment_url( $attachment_id );
//get the thumbnail
$thumb = wp_get_attachment_thumb_url( $attachment_id );
```
Not sure how to get this done in your XML file, though, so this is a partial answer, but hopefully it sends you in the right direction.
|
202,873 |
<p>I want to create a new order programatically.</p>
<p>This code works well with simple product,</p>
<pre><code> $product = get_product($product_id);
$order = wc_create_order();
$order->add_product( $product , 1 );
$order->calculate_totals();
// assign the order to the current user
update_post_meta($order->id, '_customer_user', get_current_user_id() );
// payment_complete
$order->payment_complete();
</code></pre>
<p>but when i use it for subscription product it does not add the subscription, it only add the order.</p>
|
[
{
"answer_id": 212885,
"author": "osos",
"author_id": 12185,
"author_profile": "https://wordpress.stackexchange.com/users/12185",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example </p>\n\n<pre><code> $order_data = array(\n 'status' => 'completed',\n 'customer_id' => 1,\n 'customer_note' => '',\n 'total' => '',\n );\n\n $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; // Required, else wc_create_order throws an exception\n $order = wc_create_order( $order_data );\n</code></pre>\n"
},
{
"answer_id": 217198,
"author": "Jeremy Warne",
"author_id": 77927,
"author_profile": "https://wordpress.stackexchange.com/users/77927",
"pm_score": 5,
"selected": true,
"text": "<p>Here's my code for creating a subscription -- it took a lot of trial and error to figure it all out. Best of luck!</p>\n\n<pre><code>function create_test_sub() {\n\n $email = '[email protected]';\n\n $start_date = '2015-01-01 00:00:00';\n\n $address = array(\n 'first_name' => 'Jeremy',\n 'last_name' => 'Test',\n 'company' => '',\n 'email' => $email,\n 'phone' => '777-777-777-777',\n 'address_1' => '31 Main Street',\n 'address_2' => '', \n 'city' => 'Auckland',\n 'state' => 'AKL',\n 'postcode' => '12345',\n 'country' => 'AU'\n );\n\n $default_password = wp_generate_password();\n\n if (!$user = get_user_by('login', $email)) $user = wp_create_user( $email, $default_password, $email );\n\n // I've used one product with multiple variations\n\n $parent_product = wc_get_product(22998);\n\n $args = array(\n 'attribute_billing-period' => 'Yearly',\n 'attribute_subscription-type' => 'Both'\n );\n\n $product_variation = $parent_product->get_matching_variation($args);\n\n $product = wc_get_product($product_variation); \n\n // Each variation also has its own shipping class\n\n $shipping_class = get_term_by('slug', $product->get_shipping_class(), 'product_shipping_class');\n\n WC()->shipping->load_shipping_methods();\n $shipping_methods = WC()->shipping->get_shipping_methods();\n\n // I have some logic for selecting which shipping method to use; your use case will likely be different, so figure out the method you need and store it in $selected_shipping_method\n\n $selected_shipping_method = $shipping_methods['free_shipping'];\n\n $class_cost = $selected_shipping_method->get_option('class_cost_' . $shipping_class->term_id);\n\n $quantity = 1;\n\n // As far as I can see, you need to create the order first, then the sub\n\n $order = wc_create_order(array('customer_id' => $user->id));\n\n $order->add_product( $product, $quantity, $args);\n $order->set_address( $address, 'billing' );\n $order->set_address( $address, 'shipping' );\n\n $order->add_shipping((object)array (\n 'id' => $selected_shipping_method->id,\n 'label' => $selected_shipping_method->title,\n 'cost' => (float)$class_cost,\n 'taxes' => array(),\n 'calc_tax' => 'per_order'\n ));\n\n $order->calculate_totals();\n\n $order->update_status(\"completed\", 'Imported order', TRUE);\n\n // Order created, now create sub attached to it -- optional if you're not creating a subscription, obvs\n\n // Each variation has a different subscription period\n\n $period = WC_Subscriptions_Product::get_period( $product );\n $interval = WC_Subscriptions_Product::get_interval( $product );\n\n $sub = wcs_create_subscription(array('order_id' => $order->id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date));\n\n $sub->add_product( $product, $quantity, $args);\n $sub->set_address( $address, 'billing' );\n $sub->set_address( $address, 'shipping' );\n\n $sub->add_shipping((object)array (\n 'id' => $selected_shipping_method->id,\n 'label' => $selected_shipping_method->title,\n 'cost' => (float)$class_cost,\n 'taxes' => array(),\n 'calc_tax' => 'per_order'\n ));\n\n $sub->calculate_totals();\n\n WC_Subscriptions_Manager::activate_subscriptions_for_order($order);\n\n print \"<a href='/wp-admin/post.php?post=\" . $sub->id . \"&action=edit'>Sub created! Click here to edit</a>\";\n}\n</code></pre>\n"
},
{
"answer_id": 352580,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately you must manually handle creating the subscription through code, as just adding an order does not handle it automatically.</p>\n\n<p>Here's my custom function I built based on all the answers I found on SO and digging through subscriptions code base.</p>\n\n<p>Tested with</p>\n\n<ul>\n<li>WordPress 5.2.5</li>\n<li>WooCommerce 3.8.0</li>\n<li>WooCommerce Subscriptions 2.6.1</li>\n</ul>\n\n<p><a href=\"https://gist.github.com/tripflex/a3123052f36daf18f7cb05391d752223\" rel=\"nofollow noreferrer\">https://gist.github.com/tripflex/a3123052f36daf18f7cb05391d752223</a></p>\n\n<pre><code>function give_user_subscription( $product, $user_id, $note = '' ){\n // First make sure all required functions and classes exist\n if( ! function_exists( 'wc_create_order' ) || ! function_exists( 'wcs_create_subscription' ) || ! class_exists( 'WC_Subscriptions_Product' ) ){\n return false;\n }\n\n $order = wc_create_order( array( 'customer_id' => $user_id ) );\n if( is_wp_error( $order ) ){\n return false;\n }\n\n $user = get_user_by( 'ID', $user_id );\n\n $fname = $user->first_name;\n $lname = $user->last_name;\n $email = $user->user_email;\n $address_1 = get_user_meta( $user_id, 'billing_address_1', true );\n $address_2 = get_user_meta( $user_id, 'billing_address_2', true );\n $city = get_user_meta( $user_id, 'billing_city', true );\n $postcode = get_user_meta( $user_id, 'billing_postcode', true );\n $country = get_user_meta( $user_id, 'billing_country', true );\n $state = get_user_meta( $user_id, 'billing_state', true );\n $address = array(\n 'first_name' => $fname,\n 'last_name' => $lname,\n 'email' => $email,\n 'address_1' => $address_1,\n 'address_2' => $address_2,\n 'city' => $city,\n 'state' => $state,\n 'postcode' => $postcode,\n 'country' => $country,\n );\n\n $order->set_address( $address, 'billing' );\n $order->set_address( $address, 'shipping' );\n $order->add_product( $product, 1 );\n\n $sub = wcs_create_subscription(array(\n 'order_id' => $order->get_id(),\n 'status' => 'pending', // Status should be initially set to pending to match how normal checkout process goes\n 'billing_period' => WC_Subscriptions_Product::get_period( $product ),\n 'billing_interval' => WC_Subscriptions_Product::get_interval( $product )\n ));\n\n if( is_wp_error( $sub ) ){\n return false;\n }\n\n // Modeled after WC_Subscriptions_Cart::calculate_subscription_totals()\n $start_date = gmdate( 'Y-m-d H:i:s' );\n // Add product to subscription\n $sub->add_product( $product, 1 );\n\n $dates = array(\n 'trial_end' => WC_Subscriptions_Product::get_trial_expiration_date( $product, $start_date ),\n 'next_payment' => WC_Subscriptions_Product::get_first_renewal_payment_date( $product, $start_date ),\n 'end' => WC_Subscriptions_Product::get_expiration_date( $product, $start_date ),\n );\n\n $sub->update_dates( $dates );\n $sub->calculate_totals();\n\n // Update order status with custom note\n $note = ! empty( $note ) ? $note : __( 'Programmatically added order and subscription.' );\n $order->update_status( 'completed', $note, true );\n\n // Also update subscription status to active from pending (and add note)\n $sub->update_status( 'active', $note, true );\n return $sub;\n}\n</code></pre>\n"
}
] |
2015/09/16
|
[
"https://wordpress.stackexchange.com/questions/202873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55159/"
] |
I want to create a new order programatically.
This code works well with simple product,
```
$product = get_product($product_id);
$order = wc_create_order();
$order->add_product( $product , 1 );
$order->calculate_totals();
// assign the order to the current user
update_post_meta($order->id, '_customer_user', get_current_user_id() );
// payment_complete
$order->payment_complete();
```
but when i use it for subscription product it does not add the subscription, it only add the order.
|
Here's my code for creating a subscription -- it took a lot of trial and error to figure it all out. Best of luck!
```
function create_test_sub() {
$email = '[email protected]';
$start_date = '2015-01-01 00:00:00';
$address = array(
'first_name' => 'Jeremy',
'last_name' => 'Test',
'company' => '',
'email' => $email,
'phone' => '777-777-777-777',
'address_1' => '31 Main Street',
'address_2' => '',
'city' => 'Auckland',
'state' => 'AKL',
'postcode' => '12345',
'country' => 'AU'
);
$default_password = wp_generate_password();
if (!$user = get_user_by('login', $email)) $user = wp_create_user( $email, $default_password, $email );
// I've used one product with multiple variations
$parent_product = wc_get_product(22998);
$args = array(
'attribute_billing-period' => 'Yearly',
'attribute_subscription-type' => 'Both'
);
$product_variation = $parent_product->get_matching_variation($args);
$product = wc_get_product($product_variation);
// Each variation also has its own shipping class
$shipping_class = get_term_by('slug', $product->get_shipping_class(), 'product_shipping_class');
WC()->shipping->load_shipping_methods();
$shipping_methods = WC()->shipping->get_shipping_methods();
// I have some logic for selecting which shipping method to use; your use case will likely be different, so figure out the method you need and store it in $selected_shipping_method
$selected_shipping_method = $shipping_methods['free_shipping'];
$class_cost = $selected_shipping_method->get_option('class_cost_' . $shipping_class->term_id);
$quantity = 1;
// As far as I can see, you need to create the order first, then the sub
$order = wc_create_order(array('customer_id' => $user->id));
$order->add_product( $product, $quantity, $args);
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->add_shipping((object)array (
'id' => $selected_shipping_method->id,
'label' => $selected_shipping_method->title,
'cost' => (float)$class_cost,
'taxes' => array(),
'calc_tax' => 'per_order'
));
$order->calculate_totals();
$order->update_status("completed", 'Imported order', TRUE);
// Order created, now create sub attached to it -- optional if you're not creating a subscription, obvs
// Each variation has a different subscription period
$period = WC_Subscriptions_Product::get_period( $product );
$interval = WC_Subscriptions_Product::get_interval( $product );
$sub = wcs_create_subscription(array('order_id' => $order->id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date));
$sub->add_product( $product, $quantity, $args);
$sub->set_address( $address, 'billing' );
$sub->set_address( $address, 'shipping' );
$sub->add_shipping((object)array (
'id' => $selected_shipping_method->id,
'label' => $selected_shipping_method->title,
'cost' => (float)$class_cost,
'taxes' => array(),
'calc_tax' => 'per_order'
));
$sub->calculate_totals();
WC_Subscriptions_Manager::activate_subscriptions_for_order($order);
print "<a href='/wp-admin/post.php?post=" . $sub->id . "&action=edit'>Sub created! Click here to edit</a>";
}
```
|
202,958 |
<p>I have created the following action:</p>
<pre><code>add_action( 'test_action', 'test_action' );
function test_action() {
error_log( 'test_action' );
}
</code></pre>
<p>And am calling it like this:</p>
<pre><code>error_log( 'send_test_email_in_background:START' );
wp_schedule_single_event( time(), 'test_action' );
error_log( 'send_test_email_in_background:END' );
</code></pre>
<p>What I receive in the apache error log file is this:</p>
<pre><code>[17-Sep-2015 11:09:35 UTC] send_test_email_in_background:START
[17-Sep-2015 11:09:35 UTC] send_test_email_in_background:END
</code></pre>
<p>This works exactly the same in development on my Windows PC (running WAMP) than it is on Production (running Linux in AWS). Also, if I schedule the single event 5 minutes in the future (time() + 300) it shows in my "Debug Bar Cron" plugin as being available to run in 5 minutes time and it appears to run just fine. So it appears that the CRON jobs are being created but for some reason they are not actually calling the action when running? Has anyone else had this problem or have an insight into it?</p>
|
[
{
"answer_id": 202965,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Because you're <em>scheduling</em> the event - even though it's set to run immediately (i.e. with <code>time()</code>), it won't fire until a second request. </p>\n\n<p>So that log output is entirely expected. Try running it again, removing the code, then run once more - you should get:</p>\n\n<pre><code>[time] test_action\n</code></pre>\n"
},
{
"answer_id": 362988,
"author": "Dave Hilditch",
"author_id": 19869,
"author_profile": "https://wordpress.stackexchange.com/users/19869",
"pm_score": 0,
"selected": false,
"text": "<p>If you have used a template for WordPress admin functions, you may have been inclined to insert your cron jobs inside your admin class.</p>\n\n<p>If, at the same time, your main code has an IF statement like this:</p>\n\n<pre><code>if (is_admin()) {\n foreach( glob ( PLUGIN_DIR . \"/admin/*.php\" ) as $filename ) {\n require_once( $filename );\n }\n}\n</code></pre>\n\n<p>Then this will mean the admin files will not be loaded for cron. is_admin() returns true only for when admins are visiting the wp-admin pages.</p>\n\n<p>If this is the case, you need to separate your add_action out to a file that always gets called by your plugin. You can still have your actual cron function inside your class if you wish, using a static function.</p>\n"
}
] |
2015/09/17
|
[
"https://wordpress.stackexchange.com/questions/202958",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74497/"
] |
I have created the following action:
```
add_action( 'test_action', 'test_action' );
function test_action() {
error_log( 'test_action' );
}
```
And am calling it like this:
```
error_log( 'send_test_email_in_background:START' );
wp_schedule_single_event( time(), 'test_action' );
error_log( 'send_test_email_in_background:END' );
```
What I receive in the apache error log file is this:
```
[17-Sep-2015 11:09:35 UTC] send_test_email_in_background:START
[17-Sep-2015 11:09:35 UTC] send_test_email_in_background:END
```
This works exactly the same in development on my Windows PC (running WAMP) than it is on Production (running Linux in AWS). Also, if I schedule the single event 5 minutes in the future (time() + 300) it shows in my "Debug Bar Cron" plugin as being available to run in 5 minutes time and it appears to run just fine. So it appears that the CRON jobs are being created but for some reason they are not actually calling the action when running? Has anyone else had this problem or have an insight into it?
|
Because you're *scheduling* the event - even though it's set to run immediately (i.e. with `time()`), it won't fire until a second request.
So that log output is entirely expected. Try running it again, removing the code, then run once more - you should get:
```
[time] test_action
```
|
202,988 |
<p>I'm trying to hook up some JS so that when the featured image upload box is opened and an image selected I can use Vibrant.js to analyse the colours of the selected image. The hurdle I've encountered is that I can't find any particular event to bind my function to. I've looked at various tutorials regarding the <code>wp.media()</code> object, but they all seem to involve replacing the upload box completely. Is there no straightforward way of detecting when the featured image upload window is open and the selected thumbnail preview image is loaded?</p>
|
[
{
"answer_id": 203417,
"author": "Dre",
"author_id": 60767,
"author_profile": "https://wordpress.stackexchange.com/users/60767",
"pm_score": 4,
"selected": true,
"text": "<p>After some digging I discovered that wp.media.featuredImage.frame() was what I was looking for:</p>\n\n<pre><code>wp.media.featuredImage.frame().on('open',function() {\n // Clever JS here\n});\n</code></pre>\n\n<p>I then discovered that the <code>select</code> event fires once you've clicked on the 'Set featured image' button, <em>not</em> when you've clicked on thumbnail, which was what I was after. So I bound my events to the modal window itself once it was opened:</p>\n\n<pre><code>wp.media.featuredImage.frame().on('open', function() {\n // Get the actual modal\n var modal = $(wp.media.featuredImage.frame().modal.el);\n // Do stuff when clicking on a thumbnail in the modal\n modal.on('click', '.attachment', function() {\n // Stuff and thangs\n })\n // Trigger the click event on any thumbnails selected previously\n .find('attachment.selected').trigger('click');\n});\n</code></pre>\n\n<p>The end result was that once the featured image modal was opened, it would fetch an uncropped version of the selected featured image via WP-JSON, extract the a palette of colours via <a href=\"http://jariz.github.io/vibrant.js/\" rel=\"noreferrer\">Vibrant.js</a>, and then add these as a colour picker to the modal. This let's you specify a particular colour - taken from the image - that then gets used by the theme as an overlay for that particular image. A picture explains this better:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PKEd4.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PKEd4.png\" alt=\"Colour extraction in the featured image uploader\"></a></p>\n\n<p>If anyone is interested I'll get round to writing this up in more detail in a blog post</p>\n"
},
{
"answer_id": 218493,
"author": "soderlind",
"author_id": 14546,
"author_profile": "https://wordpress.stackexchange.com/users/14546",
"pm_score": 1,
"selected": false,
"text": "<p>You can also do the following (it will also fire on the regular media modal):</p>\n\n<pre><code>jQuery(document).ready(function($){\n if (wp.media) {\n wp.media.view.Modal.prototype.on('open', function() {\n console.log('media modal open');\n });\n }\n});\n</code></pre>\n\n<p>btw, I got this snippet from <a href=\"http://dekode.no\" rel=\"nofollow\">Dekode</a></p>\n"
}
] |
2015/09/17
|
[
"https://wordpress.stackexchange.com/questions/202988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60767/"
] |
I'm trying to hook up some JS so that when the featured image upload box is opened and an image selected I can use Vibrant.js to analyse the colours of the selected image. The hurdle I've encountered is that I can't find any particular event to bind my function to. I've looked at various tutorials regarding the `wp.media()` object, but they all seem to involve replacing the upload box completely. Is there no straightforward way of detecting when the featured image upload window is open and the selected thumbnail preview image is loaded?
|
After some digging I discovered that wp.media.featuredImage.frame() was what I was looking for:
```
wp.media.featuredImage.frame().on('open',function() {
// Clever JS here
});
```
I then discovered that the `select` event fires once you've clicked on the 'Set featured image' button, *not* when you've clicked on thumbnail, which was what I was after. So I bound my events to the modal window itself once it was opened:
```
wp.media.featuredImage.frame().on('open', function() {
// Get the actual modal
var modal = $(wp.media.featuredImage.frame().modal.el);
// Do stuff when clicking on a thumbnail in the modal
modal.on('click', '.attachment', function() {
// Stuff and thangs
})
// Trigger the click event on any thumbnails selected previously
.find('attachment.selected').trigger('click');
});
```
The end result was that once the featured image modal was opened, it would fetch an uncropped version of the selected featured image via WP-JSON, extract the a palette of colours via [Vibrant.js](http://jariz.github.io/vibrant.js/), and then add these as a colour picker to the modal. This let's you specify a particular colour - taken from the image - that then gets used by the theme as an overlay for that particular image. A picture explains this better:
[](https://i.stack.imgur.com/PKEd4.png)
If anyone is interested I'll get round to writing this up in more detail in a blog post
|
202,991 |
<p>I am trying to make my own version <a href="http://demo.codestag.com/ink/" rel="nofollow">of this</a> I've implemented bootstrap grid in my attempt. I'm very close, but the <code><div class="row"></code> being looped is causing problems.</p>
<p>I want to just be able to build my html structure with bootstrap and not rely soley on the <code>if</code> statements that control how many archives are spit out. </p>
<p>Is there a way to add as many <code><?php the_post_thumbnail('category-thumbnail'); ?></code> (for example) as I want so it sequentially spits out the blogs in order?</p>
<pre><code><?php
$count = 0;
while ( have_posts() ) : the_post();
if ( $count < 1 ) { ?>
<div class="row" style="margin-bottom:0px;">
<div class="col-md-12">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php } elseif ( $count <= 2 ) { ?>
<div class="row" style="margin-bottom:0px;">
<div class="col-md-6">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
<div class="col-md-6">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php } $count++;
endwhile;
?>
</code></pre>
<p>So in the above code: I would be able to call a blog/blogs in each row, but it would the next blog in sequential order. So in this case: one that spans the whole browser and then 2 50% width ones right next to eachother, then repeat structure for more blogs.</p>
<p>Is this possible? Is there a way to make a variable or something that allows you to a call archives repeatedly while sequentially spitting out the archives and not repeating the same ones?</p>
<p>thanks in advance. </p>
|
[
{
"answer_id": 202996,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>The common loop implementation loops for <em>every</em> post. It is so pervasive that it's not obvious it being entirely optional.</p>\n\n<p>The \"every\" part comes from <code>while ( have_posts() )</code>, the advancing from <code>the_post()</code>. The former is completely technically optional.</p>\n\n<p>You can advance by one post simply calling <code>the_post()</code> and surrounding it by <em>any other logic</em> you deem necessary. Of course if your requirements are more complex then it would also take more complex logic than simple <code>while()</code>.</p>\n\n<p>I had blogged about this before <a href=\"http://www.rarst.net/wordpress/asymmetrical-loops/\" rel=\"nofollow\">Asymmetrical WordPress loops</a>.</p>\n"
},
{
"answer_id": 203021,
"author": "RLM",
"author_id": 60779,
"author_profile": "https://wordpress.stackexchange.com/users/60779",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\n$counter = 1; \n\nif(have_posts()) : while(have_posts()) : the_post(); \n?>\n<?php\nif($counter == 1) :\n?>\n <div class=\"row clear\" style=\"margin-bottom:0px;\">\n <div class=\"col-md-12 border-12\">\n <a class=\"thumb\" href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\"><?php the_post_thumbnail('category-thumbnail'); ?></a>\n <div class=\"blog-details-wrapper clear\">\n <h2 class=\"title\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n </h2>\n <span class=\"date\"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>\n <span class=\"author\"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>\n <span class=\"comments\"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>\n </div>\n </div>\n </div>\n\n<?php\n\nelseif($counter == 2) :\n?>\n\n <div class=\"row\">\n <div class=\"col-md-6 border\">\n <a class=\"thumb-6\" href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\"><?php the_post_thumbnail('category-thumbnail'); ?></a>\n <div class=\"blog-details-wrapper clear\">\n <h2 class=\"\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n </h2>\n <span class=\"date\"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>\n <span class=\"author\"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>\n <span class=\"comments\"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>\n </div>\n </div>\n\n<?php\nelseif($counter >= 2) : ?>\n\n <div class=\"col-md-6 border\">\n <a class=\"thumb-6\" href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\"><?php the_post_thumbnail('category-thumbnail'); ?></a>\n <div class=\"blog-details-wrapper clear\">\n <h2 class=\"\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n </h2>\n <span class=\"date\"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>\n <span class=\"author\"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>\n <span class=\"comments\"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>\n </div>\n </div>\n </div> \n\n<?php \n$counter = 0;\nendif;\n?>\n<?php\n$counter++;\nendwhile;\nendif;\n?>\n</code></pre>\n"
}
] |
2015/09/17
|
[
"https://wordpress.stackexchange.com/questions/202991",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60779/"
] |
I am trying to make my own version [of this](http://demo.codestag.com/ink/) I've implemented bootstrap grid in my attempt. I'm very close, but the `<div class="row">` being looped is causing problems.
I want to just be able to build my html structure with bootstrap and not rely soley on the `if` statements that control how many archives are spit out.
Is there a way to add as many `<?php the_post_thumbnail('category-thumbnail'); ?>` (for example) as I want so it sequentially spits out the blogs in order?
```
<?php
$count = 0;
while ( have_posts() ) : the_post();
if ( $count < 1 ) { ?>
<div class="row" style="margin-bottom:0px;">
<div class="col-md-12">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php } elseif ( $count <= 2 ) { ?>
<div class="row" style="margin-bottom:0px;">
<div class="col-md-6">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
<div class="col-md-6">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php } $count++;
endwhile;
?>
```
So in the above code: I would be able to call a blog/blogs in each row, but it would the next blog in sequential order. So in this case: one that spans the whole browser and then 2 50% width ones right next to eachother, then repeat structure for more blogs.
Is this possible? Is there a way to make a variable or something that allows you to a call archives repeatedly while sequentially spitting out the archives and not repeating the same ones?
thanks in advance.
|
```
<?php
$counter = 1;
if(have_posts()) : while(have_posts()) : the_post();
?>
<?php
if($counter == 1) :
?>
<div class="row clear" style="margin-bottom:0px;">
<div class="col-md-12 border-12">
<a class="thumb" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="title">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php
elseif($counter == 2) :
?>
<div class="row">
<div class="col-md-6 border">
<a class="thumb-6" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
<?php
elseif($counter >= 2) : ?>
<div class="col-md-6 border">
<a class="thumb-6" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('category-thumbnail'); ?></a>
<div class="blog-details-wrapper clear">
<h2 class="">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</h2>
<span class="date"><?php the_time('F j, Y'); ?> <?php the_time('g:i a'); ?></span>
<span class="author"><?php _e( 'Published by', 'html5blank' ); ?> <?php the_author_posts_link(); ?></span>
<span class="comments"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></span>
</div>
</div>
</div>
<?php
$counter = 0;
endif;
?>
<?php
$counter++;
endwhile;
endif;
?>
```
|
203,014 |
<p>I've got a basic text widget and, outside the standard <code><div class="textwidget"></code> wrapper there is a <code><li id="text-5" class="widget widget_text"></code> (which I have not added when creating the sidebar in <code>functions.php</code> or added when adding a text widget from the dashboard). </p>
<p>i.e. the full code looks like this:</p>
<pre><code><li id="text-5" class="widget widget_text">
<div class="textwidget">
<my content>
</div>
</li>
</code></pre>
<p>I'm at a loss where this <code>li</code> comes from. Any idea why and how I can get rid of it?</p>
|
[
{
"answer_id": 203017,
"author": "JediTricks007",
"author_id": 49017,
"author_profile": "https://wordpress.stackexchange.com/users/49017",
"pm_score": 3,
"selected": true,
"text": "<p>I think WordPress widgets create li tags on default. If you want the bullet points removed you could fix that with a css approach.</p>\n\n<pre><code>.widget li {\n list-style: none;\n}\n</code></pre>\n"
},
{
"answer_id": 259948,
"author": "diSQRL",
"author_id": 115359,
"author_profile": "https://wordpress.stackexchange.com/users/115359",
"pm_score": 0,
"selected": false,
"text": "<p>There is a truble with your wordpress theme in file \"functions.php\" there is a function for creating sidebar, there you have to add this code</p>\n\n<pre><code> 'before_widget' => '<aside id=\"%1$s\" class=\"di-widget %2$s\">',\n 'after_widget' => '</aside>',\n 'before_title' => '<h3 class=\"di-widget-title\">',\n 'after_title' => '</h3>',\n</code></pre>\n"
},
{
"answer_id": 269587,
"author": "Devsper",
"author_id": 121427,
"author_profile": "https://wordpress.stackexchange.com/users/121427",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to occur when you leave out <code>'before_widget'</code> and <code>'after_widget'</code> in the array when you register your sidebar/widget. I had the same problem and fixed it by leaving them blank. </p>\n\n<pre><code>register_sidebar( \n array( \n 'name' => 'Footer Widget',\n 'id' => 'footer-widget-1',\n 'class' => 'footer-widget',\n 'description' => 'Footer widget',\n 'before_widget' => '',\n 'after_widget' => '',\n 'before_title' => '<h3>',\n 'after_title' => '</h3>',\n ) \n);\n</code></pre>\n"
}
] |
2015/09/17
|
[
"https://wordpress.stackexchange.com/questions/203014",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48904/"
] |
I've got a basic text widget and, outside the standard `<div class="textwidget">` wrapper there is a `<li id="text-5" class="widget widget_text">` (which I have not added when creating the sidebar in `functions.php` or added when adding a text widget from the dashboard).
i.e. the full code looks like this:
```
<li id="text-5" class="widget widget_text">
<div class="textwidget">
<my content>
</div>
</li>
```
I'm at a loss where this `li` comes from. Any idea why and how I can get rid of it?
|
I think WordPress widgets create li tags on default. If you want the bullet points removed you could fix that with a css approach.
```
.widget li {
list-style: none;
}
```
|
203,027 |
<p>So I have a client who wants a little extra that is beyond capabilities of my wordpress theme that I have purchased. I know through html, css and js I can create it from scratch (they want animations and a neat looking landing page). I was wondering if there was a way or any plugins that I can use to directly create a page using all of the code. Sorry if I am not explaining my question well! </p>
|
[
{
"answer_id": 203017,
"author": "JediTricks007",
"author_id": 49017,
"author_profile": "https://wordpress.stackexchange.com/users/49017",
"pm_score": 3,
"selected": true,
"text": "<p>I think WordPress widgets create li tags on default. If you want the bullet points removed you could fix that with a css approach.</p>\n\n<pre><code>.widget li {\n list-style: none;\n}\n</code></pre>\n"
},
{
"answer_id": 259948,
"author": "diSQRL",
"author_id": 115359,
"author_profile": "https://wordpress.stackexchange.com/users/115359",
"pm_score": 0,
"selected": false,
"text": "<p>There is a truble with your wordpress theme in file \"functions.php\" there is a function for creating sidebar, there you have to add this code</p>\n\n<pre><code> 'before_widget' => '<aside id=\"%1$s\" class=\"di-widget %2$s\">',\n 'after_widget' => '</aside>',\n 'before_title' => '<h3 class=\"di-widget-title\">',\n 'after_title' => '</h3>',\n</code></pre>\n"
},
{
"answer_id": 269587,
"author": "Devsper",
"author_id": 121427,
"author_profile": "https://wordpress.stackexchange.com/users/121427",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to occur when you leave out <code>'before_widget'</code> and <code>'after_widget'</code> in the array when you register your sidebar/widget. I had the same problem and fixed it by leaving them blank. </p>\n\n<pre><code>register_sidebar( \n array( \n 'name' => 'Footer Widget',\n 'id' => 'footer-widget-1',\n 'class' => 'footer-widget',\n 'description' => 'Footer widget',\n 'before_widget' => '',\n 'after_widget' => '',\n 'before_title' => '<h3>',\n 'after_title' => '</h3>',\n ) \n);\n</code></pre>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203027",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80568/"
] |
So I have a client who wants a little extra that is beyond capabilities of my wordpress theme that I have purchased. I know through html, css and js I can create it from scratch (they want animations and a neat looking landing page). I was wondering if there was a way or any plugins that I can use to directly create a page using all of the code. Sorry if I am not explaining my question well!
|
I think WordPress widgets create li tags on default. If you want the bullet points removed you could fix that with a css approach.
```
.widget li {
list-style: none;
}
```
|
203,062 |
<p>I am a little confused by this. I have a query that finds posts within a category and date.</p>
<p>I can filter the categories, but I have no idea how to filter by date.</p>
<p>The query works. I see all of the posts I have queried, but I don't know how to filter the date. It would help if I knew what was meant to appear in the url</p>
<p>The search for categories returns /blog/?category=promotions</p>
<p>What should a date filter result look like?</p>
<pre><code><?php $categorys = get_terms( 'category', array( 'hide_empty' => true, 'fields' => 'all' ) ); ?>
<form class="staff-filter" method="GET" action=""><div class="col-sm-12 text-center">
<span>Filter Posts by:</span>
<ul class="list-inline">
<li>
<label>
<select name="category">
<option value="" disabled selected> Category </option>
<?php foreach( $categorys as $category ) : ?>
<option value="<?php echo $category->slug; ?>">
<?php echo $category->name; ?>
</option>
<?php endforeach; ?>
</select>
</label>
</li>
<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
$months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>
<li>
<select name="date_start">
<option value="" disabled selected> Date </option>
<?php foreach($months as $month) : ?>
<option> <?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .'/'.$year .'/'.date('m', strtotime($month)).'"/> ' . $month .'</a></li></ul>';?></option>
<?php endforeach; ?>
<?php foreach($years as $year) : ?>
<option><?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .''.$year.'"/> ' . $year .'</a></li></ul>';?></option>
<?php endforeach; ?>
</select>
</li>
</ul>
<!-- SUBMIT BUTTON -->
<button class="btn"><span class="glyphicon glyphicon-search" aria-hidden="true"> </span> Search</button>
<!-- END SUBMIT BUTTON -->
</div>
</form>
<?php
$cat_query = array(array('relation' => 'AND'));
if( isset( $_GET['category'] ) && $_GET['category'] ){
$cat_area_query = array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $_GET['category'],'operator' => 'IN', );
$cat_query[] = $cat_area_query;
}
if( $cat_query && $cat_query ){
$cat_query['relation'] = 'AND'
;
}
$args = array(
'post_type' => array('post'),
'post_status' => 'publish',
'tax_query' => $cat_query,
'orderby' => 'date',
'order' => 'desc',
'date_query' => array(
'relation' => 'OR',
array(
'year' => $getdate['year'],
'month' => array(9, 8,7, 6, 5),
'compare' => '=',
),
),
);?>
$posts_query = new WP_Query( $args );?>
<?php if( $posts_query->have_posts() ) : ?>
<?php while( $posts_query->have_posts() ) : $posts_query->the_post(); ?>
<div class="ms-item col-lg-6 col-md-6 col-sm-6 col-xs-12">
<?php if (has_post_thumbnail()) : ?>
<figure class="article-preview-image">
<a href="<?php the_permalink(); ?>" class="post-title-link"><?php the_post_thumbnail(); ?></a>
</figure>
<?php else : ?>
<?php endif; ?>
<a href="<?php the_permalink(); ?>">
<div class="post-content white">
<?php $category = get_the_category(); ?>
<span class="post-category"><?php echo $category[0]->cat_name;?></span>
<span class="post-date"><i class="fa fa-clock-o"></i> <?php the_time('F j, Y') ?></span>
<h2 class="post-title"><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</div>
</a>
<?php endwhile;?>
</code></pre>
<p><a href="http://pastebin.com/VP93YY5w" rel="nofollow">Link to pastebin</a></p>
|
[
{
"answer_id": 203322,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 2,
"selected": true,
"text": "<p>I was going about this the wrong way around. I needed to allow the user to select the date first and then the category.</p>\n\n<p>I also needed to make the dropdown boxes auto select, so that the date search is performed first taking the user to the date archive and then the user can select the category they require.</p>\n\n<pre><code><form class=\"my-filter\" method=\"GET\" action=\"\"><div class=\"col-sm-12 text-center\">\n <span>Filter Posts by:</span>\n <ul class=\"list-inline\">\n <?php $years = $wpdb->get_col(\"SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC\");\n $months = $wpdb->get_col(\"SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC\");?>\n <li>\n <select onChange=\"window.location.href=this.value\">\n <option value=\"\" disabled selected> Date </option>\n <?php foreach($months as $month) : ?>\n <option value=\"<?php echo site_url() .'/'.date('Y') .'/'.date('m', strtotime($month))?>\"> <?php echo '<ul><li class\"list-unstyled\">' . $month .'</li></ul>';?></option>\n <?php endforeach; ?>\n\n <?php foreach($years as $year) : ?>\n <option value=\"<?php echo site_url() .'/'.$year ?>\"><?php echo '<ul><li class\"list-unstyled\">' . $year .'</li></ul>';?></option>\n <?php endforeach; ?> \n </select>\n </li>\n <li>\n <label>\n <select onChange=\"window.location.href=this.value\">\n <option value=\"category\" disabled selected> Category </option>\n <?php foreach( $categorys as $category ) : ?>\n <option value=\"?category=<?php echo $category->slug; ?>\">\n <?php echo $category->name; ?>\n </option>\n <?php endforeach; ?>\n </select>\n </label>\n </li> \n </ul> \n </div>\n </form>\n</code></pre>\n\n<p>Now the final url reads</p>\n\n<pre><code>http://mywebsite.com/2015/09/?category=special-events\n</code></pre>\n\n<p>To make sure that the query finds the category only for that month the $args must include a dynamic date_query like this:</p>\n\n<pre><code>$m = get_the_time('m');\n$y = get_the_time('Y');\n\n$args = array(\n 'post_type' => array('post'),\n 'post_status' => 'publish',\n 'tax_query' => $cat_query,\n 'orderby' => 'date',\n 'order' => 'desc',\n 'date_query' => array(\n array(\n 'year' => $y,\n 'month' => $m,\n ),\n), \n\n);\n</code></pre>\n"
},
{
"answer_id": 401853,
"author": "tiadotdev",
"author_id": 83771,
"author_profile": "https://wordpress.stackexchange.com/users/83771",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone else looking to filter by date WITHOUT the URL component, this is what I ended up using this for the form:</p>\n<pre><code><!-- Filter Form -->\n<form method="GET" action="/research-submissions/" id="submissionsFilterForm">\n <div class="filter-form--content">\n <div class="filter-items">\n\n <!-- Years -->\n <div class="filter-item year">\n <?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC"); ?>\n <select name="years[]">\n <option disabled selected><?php _e('Year', 'twentytwentyone'); ?></option>\n <?php foreach($years as $year) : ?>\n <option \n value="<?= $year; ?>"\n <?php echo selected(\n (isset($_GET['years']) && in_array($year, $_GET['years']))\n ) ?>\n ><?= $year; ?></option>\n <?php endforeach; ?>\n </select>\n </div>\n \n </div> \n <div class="category-filters--submit">\n <button type="submit" name=""><?php _e('Search', 'twentytwentyone'); ?></button>\n </div>\n </div>\n</form> \n</code></pre>\n<p>And this for the wp_query with args:</p>\n<pre><code><!-- Results -->\n<div class="submissions-content">\n \n <?php \n \n // Years\n if($_GET['years'] && !empty($_GET['years'])) {\n $yearsF = $_GET['years'];\n foreach ($yearsF as $yearF) {\n $year_filter = $yearF;\n }\n }\n \n global $post;\n\n $date_query = array('relation' => 'AND');\n if( isset($_GET['years']) ) {\n $date_query[] = array(\n 'year' => $year_filter,\n );\n }\n \n $args = array(\n 'post_type' => array('post'),\n 'posts_per_page' => -1,\n 'date_query' => $date_query,\n );\n \n $query = new WP_Query($args);\n if ( $query->have_posts() ) : \n while($query -> have_posts()) : $query -> the_post();\n\n $title = get_the_title($post->ID); \n $date = get_the_date( 'F j, Y' ); ?>\n\n <div class="single-post submission">\n <h3><?= $title; ?></h3>\n <time><?= $date; ?></time>\n </div>\n \n <?php endwhile;\n \n else : ?>\n\n <div class="single-post error">\n <?php _e('Oops! Nothing matches your search', 'twentytwentyone'); ?>. <span><?php _e('Try again', 'twentytwentyone'); ?></span>.\n </div>\n\n <?php endif;\n \n wp_reset_query(); ?>\n \n</div>\n</code></pre>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69240/"
] |
I am a little confused by this. I have a query that finds posts within a category and date.
I can filter the categories, but I have no idea how to filter by date.
The query works. I see all of the posts I have queried, but I don't know how to filter the date. It would help if I knew what was meant to appear in the url
The search for categories returns /blog/?category=promotions
What should a date filter result look like?
```
<?php $categorys = get_terms( 'category', array( 'hide_empty' => true, 'fields' => 'all' ) ); ?>
<form class="staff-filter" method="GET" action=""><div class="col-sm-12 text-center">
<span>Filter Posts by:</span>
<ul class="list-inline">
<li>
<label>
<select name="category">
<option value="" disabled selected> Category </option>
<?php foreach( $categorys as $category ) : ?>
<option value="<?php echo $category->slug; ?>">
<?php echo $category->name; ?>
</option>
<?php endforeach; ?>
</select>
</label>
</li>
<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
$months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>
<li>
<select name="date_start">
<option value="" disabled selected> Date </option>
<?php foreach($months as $month) : ?>
<option> <?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .'/'.$year .'/'.date('m', strtotime($month)).'"/> ' . $month .'</a></li></ul>';?></option>
<?php endforeach; ?>
<?php foreach($years as $year) : ?>
<option><?php echo '<ul><li class"list-unstyled"><a href="'. site_url() .''.$year.'"/> ' . $year .'</a></li></ul>';?></option>
<?php endforeach; ?>
</select>
</li>
</ul>
<!-- SUBMIT BUTTON -->
<button class="btn"><span class="glyphicon glyphicon-search" aria-hidden="true"> </span> Search</button>
<!-- END SUBMIT BUTTON -->
</div>
</form>
<?php
$cat_query = array(array('relation' => 'AND'));
if( isset( $_GET['category'] ) && $_GET['category'] ){
$cat_area_query = array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $_GET['category'],'operator' => 'IN', );
$cat_query[] = $cat_area_query;
}
if( $cat_query && $cat_query ){
$cat_query['relation'] = 'AND'
;
}
$args = array(
'post_type' => array('post'),
'post_status' => 'publish',
'tax_query' => $cat_query,
'orderby' => 'date',
'order' => 'desc',
'date_query' => array(
'relation' => 'OR',
array(
'year' => $getdate['year'],
'month' => array(9, 8,7, 6, 5),
'compare' => '=',
),
),
);?>
$posts_query = new WP_Query( $args );?>
<?php if( $posts_query->have_posts() ) : ?>
<?php while( $posts_query->have_posts() ) : $posts_query->the_post(); ?>
<div class="ms-item col-lg-6 col-md-6 col-sm-6 col-xs-12">
<?php if (has_post_thumbnail()) : ?>
<figure class="article-preview-image">
<a href="<?php the_permalink(); ?>" class="post-title-link"><?php the_post_thumbnail(); ?></a>
</figure>
<?php else : ?>
<?php endif; ?>
<a href="<?php the_permalink(); ?>">
<div class="post-content white">
<?php $category = get_the_category(); ?>
<span class="post-category"><?php echo $category[0]->cat_name;?></span>
<span class="post-date"><i class="fa fa-clock-o"></i> <?php the_time('F j, Y') ?></span>
<h2 class="post-title"><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</div>
</a>
<?php endwhile;?>
```
[Link to pastebin](http://pastebin.com/VP93YY5w)
|
I was going about this the wrong way around. I needed to allow the user to select the date first and then the category.
I also needed to make the dropdown boxes auto select, so that the date search is performed first taking the user to the date archive and then the user can select the category they require.
```
<form class="my-filter" method="GET" action=""><div class="col-sm-12 text-center">
<span>Filter Posts by:</span>
<ul class="list-inline">
<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
$months = $wpdb->get_col("SELECT DISTINCT MONTHNAME(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");?>
<li>
<select onChange="window.location.href=this.value">
<option value="" disabled selected> Date </option>
<?php foreach($months as $month) : ?>
<option value="<?php echo site_url() .'/'.date('Y') .'/'.date('m', strtotime($month))?>"> <?php echo '<ul><li class"list-unstyled">' . $month .'</li></ul>';?></option>
<?php endforeach; ?>
<?php foreach($years as $year) : ?>
<option value="<?php echo site_url() .'/'.$year ?>"><?php echo '<ul><li class"list-unstyled">' . $year .'</li></ul>';?></option>
<?php endforeach; ?>
</select>
</li>
<li>
<label>
<select onChange="window.location.href=this.value">
<option value="category" disabled selected> Category </option>
<?php foreach( $categorys as $category ) : ?>
<option value="?category=<?php echo $category->slug; ?>">
<?php echo $category->name; ?>
</option>
<?php endforeach; ?>
</select>
</label>
</li>
</ul>
</div>
</form>
```
Now the final url reads
```
http://mywebsite.com/2015/09/?category=special-events
```
To make sure that the query finds the category only for that month the $args must include a dynamic date\_query like this:
```
$m = get_the_time('m');
$y = get_the_time('Y');
$args = array(
'post_type' => array('post'),
'post_status' => 'publish',
'tax_query' => $cat_query,
'orderby' => 'date',
'order' => 'desc',
'date_query' => array(
array(
'year' => $y,
'month' => $m,
),
),
);
```
|
203,077 |
<p>Here's the query i have used.</p>
<pre><code> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&paged=' . $paged); ?>
</code></pre>
<p>Is there any way to skip the first 3 posts only in the first page (?paged=1) and not the other pages (?paged=2....).</p>
|
[
{
"answer_id": 203078,
"author": "Steed-Asprey",
"author_id": 75166,
"author_profile": "https://wordpress.stackexchange.com/users/75166",
"pm_score": 0,
"selected": false,
"text": "<p>By using the offset parameter: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters</a></p>\n\n<pre><code>$wp_query = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged); ?>\n</code></pre>\n"
},
{
"answer_id": 203082,
"author": "Deepak kumar",
"author_id": 15858,
"author_profile": "https://wordpress.stackexchange.com/users/15858",
"pm_score": 3,
"selected": false,
"text": "<p>For skipping the post just use offset parameter in wp_query.</p>\n\n<p>To display latest three post :</p>\n\n<pre><code><?php\n$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');\n\n//Here add loop to display posts like\n\nwhile($latestpost->have_posts()) : $latestpost->the_post();\n\nthe_title();\n\nthe_content();\n\nendwhile; wp_reset_query();\n\n//After that skip three posts using offset\n\n $latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged); \n\nthe_title();\n\nthe_content();\n\nendwhile; wp_reset_query();\n\n?>\n</code></pre>\n\n<p>That's it</p>\n"
},
{
"answer_id": 203109,
"author": "Megh Gandhi",
"author_id": 80611,
"author_profile": "https://wordpress.stackexchange.com/users/80611",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.smashingmagazine.com/2009/06/10-useful-wordpress-loop-hacks/#2-use-more-than-one-loop-on-a-page-without-printing-duplicate-posts\" rel=\"nofollow\">http://www.smashingmagazine.com/2009/06/10-useful-wordpress-loop-hacks/#2-use-more-than-one-loop-on-a-page-without-printing-duplicate-posts</a> </p>\n\n<p>Well i just followed this method and made some changes to it...</p>\n\n<pre><code>// in functions.php\n$mega = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');\n//set the posts per page to 3 so the id's of the first 3 posts will be shown \n$ids = array();\nwhile ($mega->have_posts()) : $mega->the_post();\n$ids[] = get_the_ID();\n\nendwhile;\n</code></pre>\n\n<p>After that to the main loop for skipping first three posts loop which i changed a bit. </p>\n\n<pre><code> $args= array(\n'post_type' => 'post',\n'posts_per_page' => 6,\n'paged' => $paged,\n'order'=> 'asc',\n'orderby'=> 'meta_value',\n'meta_key'=>'date',\n'post__not_in' => $ids\n\n );\n $wp_query = new WP_Query($args);\n</code></pre>\n\n<p>And it works like i wanted..</p>\n"
},
{
"answer_id": 244312,
"author": "Aric Harris",
"author_id": 105872,
"author_profile": "https://wordpress.stackexchange.com/users/105872",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using the <code>offset</code> attribute have you thought about creating a var with a value of 1 is incremented in the loop. If the loop if less than 4 do nothing, else </p>\n\n<pre><code><?php\n $p=1;\n while ( have_posts() ) : the_post();\n if($p > 3) {\n?>\n// DO STUFF\n</code></pre>\n\n \n\n<p>This doesn't address the issue, but you may be able to set a condition that if this is the first page then skip the first 3? </p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80611/"
] |
Here's the query i have used.
```
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&paged=' . $paged); ?>
```
Is there any way to skip the first 3 posts only in the first page (?paged=1) and not the other pages (?paged=2....).
|
For skipping the post just use offset parameter in wp\_query.
To display latest three post :
```
<?php
$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');
//Here add loop to display posts like
while($latestpost->have_posts()) : $latestpost->the_post();
the_title();
the_content();
endwhile; wp_reset_query();
//After that skip three posts using offset
$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged);
the_title();
the_content();
endwhile; wp_reset_query();
?>
```
That's it
|
203,091 |
<p>Lets say you have a custom template and you want to implement a title of Wordpress template
for section /category/general where general is a category name . </p>
<p>How to implement category page titile for this page .</p>
<p>I tried with </p>
<pre><code> <h2><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ? >"><?php the_title(); ?></a></h2>
</code></pre>
<p>But this does not work as a clickable link . </p>
|
[
{
"answer_id": 203078,
"author": "Steed-Asprey",
"author_id": 75166,
"author_profile": "https://wordpress.stackexchange.com/users/75166",
"pm_score": 0,
"selected": false,
"text": "<p>By using the offset parameter: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters</a></p>\n\n<pre><code>$wp_query = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged); ?>\n</code></pre>\n"
},
{
"answer_id": 203082,
"author": "Deepak kumar",
"author_id": 15858,
"author_profile": "https://wordpress.stackexchange.com/users/15858",
"pm_score": 3,
"selected": false,
"text": "<p>For skipping the post just use offset parameter in wp_query.</p>\n\n<p>To display latest three post :</p>\n\n<pre><code><?php\n$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');\n\n//Here add loop to display posts like\n\nwhile($latestpost->have_posts()) : $latestpost->the_post();\n\nthe_title();\n\nthe_content();\n\nendwhile; wp_reset_query();\n\n//After that skip three posts using offset\n\n $latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged); \n\nthe_title();\n\nthe_content();\n\nendwhile; wp_reset_query();\n\n?>\n</code></pre>\n\n<p>That's it</p>\n"
},
{
"answer_id": 203109,
"author": "Megh Gandhi",
"author_id": 80611,
"author_profile": "https://wordpress.stackexchange.com/users/80611",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.smashingmagazine.com/2009/06/10-useful-wordpress-loop-hacks/#2-use-more-than-one-loop-on-a-page-without-printing-duplicate-posts\" rel=\"nofollow\">http://www.smashingmagazine.com/2009/06/10-useful-wordpress-loop-hacks/#2-use-more-than-one-loop-on-a-page-without-printing-duplicate-posts</a> </p>\n\n<p>Well i just followed this method and made some changes to it...</p>\n\n<pre><code>// in functions.php\n$mega = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');\n//set the posts per page to 3 so the id's of the first 3 posts will be shown \n$ids = array();\nwhile ($mega->have_posts()) : $mega->the_post();\n$ids[] = get_the_ID();\n\nendwhile;\n</code></pre>\n\n<p>After that to the main loop for skipping first three posts loop which i changed a bit. </p>\n\n<pre><code> $args= array(\n'post_type' => 'post',\n'posts_per_page' => 6,\n'paged' => $paged,\n'order'=> 'asc',\n'orderby'=> 'meta_value',\n'meta_key'=>'date',\n'post__not_in' => $ids\n\n );\n $wp_query = new WP_Query($args);\n</code></pre>\n\n<p>And it works like i wanted..</p>\n"
},
{
"answer_id": 244312,
"author": "Aric Harris",
"author_id": 105872,
"author_profile": "https://wordpress.stackexchange.com/users/105872",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using the <code>offset</code> attribute have you thought about creating a var with a value of 1 is incremented in the loop. If the loop if less than 4 do nothing, else </p>\n\n<pre><code><?php\n $p=1;\n while ( have_posts() ) : the_post();\n if($p > 3) {\n?>\n// DO STUFF\n</code></pre>\n\n \n\n<p>This doesn't address the issue, but you may be able to set a condition that if this is the first page then skip the first 3? </p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80617/"
] |
Lets say you have a custom template and you want to implement a title of Wordpress template
for section /category/general where general is a category name .
How to implement category page titile for this page .
I tried with
```
<h2><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ? >"><?php the_title(); ?></a></h2>
```
But this does not work as a clickable link .
|
For skipping the post just use offset parameter in wp\_query.
To display latest three post :
```
<?php
$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=3');
//Here add loop to display posts like
while($latestpost->have_posts()) : $latestpost->the_post();
the_title();
the_content();
endwhile; wp_reset_query();
//After that skip three posts using offset
$latestpost = new WP_Query('order=asc&orderby=meta_value&meta_key=date&posts_per_page=6&offset=3&paged=' . $paged);
the_title();
the_content();
endwhile; wp_reset_query();
?>
```
That's it
|
203,092 |
<p>i make a custom post type in WordPress and i also make its separate two pages single-acme_product.php, archive-acme_product.php but the issue is when i upload the post from custom post type its show index.php </p>
<p>here is my code of function </p>
<pre><code>function new_post_type_wp(){
register_post_type('acme_product',
array(
'labels' => array(
'name' => __('Products'),
'singular_name' => __('Product')
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init','new_post_type_wp');
</code></pre>
<p>please tell me how to i navigate my custom post to specific custom page i also read wordpress codex its very help full i follow its method but my issue is same kindly help me</p>
<p>reference link : <a href="https://codex.wordpress.org/Post_Types" rel="nofollow">https://codex.wordpress.org/Post_Types</a></p>
|
[
{
"answer_id": 203098,
"author": "user57831",
"author_id": 57831,
"author_profile": "https://wordpress.stackexchange.com/users/57831",
"pm_score": -1,
"selected": false,
"text": "<p>Alright, if I am not wrong with your request, below solutions may help.\n1. make you sing-acme_product.php as a template, eg:</p>\n\n<pre><code> <?php\n /**\n Template Name: the new of the template\n */\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Use WP_Query, eg:</p>\n\n<p>$products = new WP_Query('post_type = products'); \nif($products->have_posts()) : while($products->have_posts()):$products->the_post();</p>\n\n<p>endwhile; endif; wp_reset_postdata();</p></li>\n</ol>\n\n<p>Hope this will help.</p>\n"
},
{
"answer_id": 203103,
"author": "deflime",
"author_id": 18907,
"author_profile": "https://wordpress.stackexchange.com/users/18907",
"pm_score": 1,
"selected": true,
"text": "<p>Since WordPress is having trouble recognizing your custom template files, you could use this instead.</p>\n\n<p>Insert into your <code>single.php</code> file. Based on your description above, it sounds like you don't have a <code>single.php</code> file so you will likely have to create one. If you do already have a <code>single.php</code> file then there is likely still some confusion with your exact problem because a custom post would only display the <code>index.php</code> template if there was no <code>single.php</code>. Or you could just be confusing the two.</p>\n\n<pre><code><?php \n if( get_post_type == 'acme_product' ) {\n // Put the template code to display the custom post type post\n\n } else {\n // Code for all other posts\n\n }\n?>\n</code></pre>\n\n<p>This will work in any of the default WordPress post related template files like categories, archives, etc.</p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79858/"
] |
i make a custom post type in WordPress and i also make its separate two pages single-acme\_product.php, archive-acme\_product.php but the issue is when i upload the post from custom post type its show index.php
here is my code of function
```
function new_post_type_wp(){
register_post_type('acme_product',
array(
'labels' => array(
'name' => __('Products'),
'singular_name' => __('Product')
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init','new_post_type_wp');
```
please tell me how to i navigate my custom post to specific custom page i also read wordpress codex its very help full i follow its method but my issue is same kindly help me
reference link : <https://codex.wordpress.org/Post_Types>
|
Since WordPress is having trouble recognizing your custom template files, you could use this instead.
Insert into your `single.php` file. Based on your description above, it sounds like you don't have a `single.php` file so you will likely have to create one. If you do already have a `single.php` file then there is likely still some confusion with your exact problem because a custom post would only display the `index.php` template if there was no `single.php`. Or you could just be confusing the two.
```
<?php
if( get_post_type == 'acme_product' ) {
// Put the template code to display the custom post type post
} else {
// Code for all other posts
}
?>
```
This will work in any of the default WordPress post related template files like categories, archives, etc.
|
203,094 |
<p>My blog (Jetpack) sends out <code>512x512</code> favicon as <code>og:image</code>, because theme used does not support featured images and there are no images / gallery in the post itself. I'm forced to use favicons that large, because Wordpress / theme says:</p>
<blockquote>
<p>The Site Icon is used as a browser and app icon for your site. Icons must be square, and at least 512 pixels wide and tall.</p>
</blockquote>
<p>Is there any solution, that would allow me to block <code>og:image</code> tag <strong>only for favicon</strong> (i.e. if there will be any images directly in post text or if I change my theme to one, that supports featured images, I want them to be exported as <code>og:image</code>; I only want to block sending favicon / Site Icon through this tag).</p>
<p><strong>Edit</strong>: <em>As per <a href="https://jetpack.com/2013/10/15/add-a-default-fallback-image-if-no-image/" rel="nofollow">Jetpack Blog</a> I have assumed, that the quickest solution will be to ignore above text and set my favicon to i.e. <code>192x192</code>, which Facebook should ignore. However, some tests with <a href="https://developers.facebook.com/tools/debug/" rel="nofollow">Facebook Debugger</a> showed, that this not always works (image isn't sometimes ignored) and this will certainly not work for other kind of social sharing services. Thus, an ability to blog <code>og:image</code> tag for favicons / Site Icons becomes really necessary.</em></p>
|
[
{
"answer_id": 228606,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>If you know the name of the function that is adding the meta tag (and it's added in it's own).</p>\n\n<pre><code>function se_remove_meta() {\n remove_action('wp_head', 'function_name');\n}\nadd_action( 'init', 'se_remove_meta' );\n</code></pre>\n"
},
{
"answer_id": 228649,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Probably through Jetpack, yet I'm not sure</p>\n</blockquote>\n\n<p>Looking at your site now I can say that those open graph tags are from <code>Jetpack</code> Plugin.</p>\n\n<hr>\n\n<p>If there is no image available in the post , Jetpack adds site-icon/favicon as the default one.</p>\n\n<p>We can control output of tags using filters</p>\n\n<ul>\n<li><strong><code>jetpack_open_graph_tags</code></strong></li>\n<li><strong><code>jetpack_images_get_images</code></strong></li>\n<li><strong><code>jetpack_open_graph_image_default</code></strong></li>\n<li><strong><code>jetpack_enable_open_graph</code></strong></li>\n</ul>\n\n<h1>Remove only og:image</h1>\n\n<p>Place the following code in <code>functions.php</code> of the active theme.</p>\n\n<pre><code>function wpse_228649_remove_image_tag( $tags ) {\n unset( $tags['og:image'] );\n return $tags;\n}\nadd_filter( 'jetpack_open_graph_tags', 'wpse_228649_remove_image_tag' );\n</code></pre>\n\n<p>Stating from <a href=\"https://jetpack.com/2013/10/15/add-a-default-fallback-image-if-no-image/\" rel=\"nofollow\">Jetpack blog</a> </p>\n\n<p>Jetpack starts by looking for a Featured Image. If you didn’t define any, we will look for slideshows and galleries, and then for any images that may be attached to the post. If we don’t find any image attached to that post, we’ll look for single images you may have inserted in the post. If you’ve inserted an image that is hosted on another site, we can use it too.</p>\n\n<p>However, sometimes you may not have added any image to your post. \nIn that case , we can set default image using the following code.</p>\n\n<pre><code>function wpse_203094_custom_image( $media, $post_id, $args ) {\n if ( $media ) {\n return $media;\n } else {\n $permalink = get_permalink( $post_id );\n $url = 'YOUR_CUSTOM_DEFAULT_IMAGE_URL' ;\n\n return array( array(\n 'type' => 'image',\n 'from' => 'custom_fallback',\n 'src' => esc_url( $url ),\n 'href' => $permalink,\n ) );\n }\n}\nadd_filter( 'jetpack_images_get_images', 'wpse_203094_custom_image', 10, 3 );\n</code></pre>\n\n<p>Or you can use filter to change the default one.</p>\n\n<pre><code>function wpse_203094_jetpack_default_image() {\n return 'YOUR_IMAGE_URL';\n}\nadd_filter( 'jetpack_open_graph_image_default', 'wpse_203094_jetpack_default_image' );\n</code></pre>\n\n<p>Or you can disable them entirely using:</p>\n\n<pre><code>add_filter( 'jetpack_enable_open_graph', '__return_false' );\n</code></pre>\n\n<h1>Note</h1>\n\n<p>As <strong>@cjbj</strong> pointed out that some plugins like <code>Yoast SEO</code> can override open graph tags. The above filters/code works only for <code>Jetpack</code> assuming that no other plugins are overriding them.</p>\n\n<h2>Update</h2>\n\n<blockquote>\n <p>Is there any solution, that would allow me to block og:image tag only for favicon</p>\n</blockquote>\n\n<p>Yes there is , we can use <a href=\"https://github.com/Automattic/jetpack/blob/4.0.3/class.jetpack-post-images.php/#L496\" rel=\"nofollow\"><strong><code>jetpack_images_get_images</code></strong></a> filter.If we take a look at <a href=\"https://github.com/Automattic/jetpack/blob/4.0.3/functions.opengraph.php/#L340\" rel=\"nofollow\"><strong><code>jetpack_og_get_image</code></strong></a> src we can find that it adds core site icon like this</p>\n\n<pre><code>// Third fall back, Core Site Icon. Added in WP 4.3.\n\nif ( empty( $image ) && ( function_exists( 'has_site_icon') && has_site_icon() ) ) {\n $image['src'] = get_site_icon_url( 512 );\n $image['width'] = '512';\n $image['height'] = '512';\n}\n</code></pre>\n\n<p>And finally defaults to blank image like this </p>\n\n<pre><code>// Finally fall back, blank image\nif ( empty( $image ) ) {\n /**\n * Filter the default Open Graph Image tag, used when no Image can be found in a post.\n *\n * @since 3.0.0\n *\n * @param string $str Default Image URL.\n */\n $image['src'] = apply_filters( 'jetpack_open_graph_image_default', 'https://s0.wp.com/i/blank.jpg' );\n}\n</code></pre>\n\n<p>So as to make Jetpack assume that it has already got an image and there is no need to use <code>site icon</code>, we need to set some image.This can be done using the following code.Place this in <code>functions.php</code> of the active theme.</p>\n\n<pre><code>function wpse_203094_no_site_icon( $media, $post_id, $args ) {\n if ( $media ) {\n return $media;\n } else {\n return array( array(\n 'src' => '' // here we are conning Jetpack, Hurray!\n ) );\n }\n}\nadd_filter( 'jetpack_images_get_images', 'wpse_203094_no_site_icon', 10, 3 );\n</code></pre>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17323/"
] |
My blog (Jetpack) sends out `512x512` favicon as `og:image`, because theme used does not support featured images and there are no images / gallery in the post itself. I'm forced to use favicons that large, because Wordpress / theme says:
>
> The Site Icon is used as a browser and app icon for your site. Icons must be square, and at least 512 pixels wide and tall.
>
>
>
Is there any solution, that would allow me to block `og:image` tag **only for favicon** (i.e. if there will be any images directly in post text or if I change my theme to one, that supports featured images, I want them to be exported as `og:image`; I only want to block sending favicon / Site Icon through this tag).
**Edit**: *As per [Jetpack Blog](https://jetpack.com/2013/10/15/add-a-default-fallback-image-if-no-image/) I have assumed, that the quickest solution will be to ignore above text and set my favicon to i.e. `192x192`, which Facebook should ignore. However, some tests with [Facebook Debugger](https://developers.facebook.com/tools/debug/) showed, that this not always works (image isn't sometimes ignored) and this will certainly not work for other kind of social sharing services. Thus, an ability to blog `og:image` tag for favicons / Site Icons becomes really necessary.*
|
>
> Probably through Jetpack, yet I'm not sure
>
>
>
Looking at your site now I can say that those open graph tags are from `Jetpack` Plugin.
---
If there is no image available in the post , Jetpack adds site-icon/favicon as the default one.
We can control output of tags using filters
* **`jetpack_open_graph_tags`**
* **`jetpack_images_get_images`**
* **`jetpack_open_graph_image_default`**
* **`jetpack_enable_open_graph`**
Remove only og:image
====================
Place the following code in `functions.php` of the active theme.
```
function wpse_228649_remove_image_tag( $tags ) {
unset( $tags['og:image'] );
return $tags;
}
add_filter( 'jetpack_open_graph_tags', 'wpse_228649_remove_image_tag' );
```
Stating from [Jetpack blog](https://jetpack.com/2013/10/15/add-a-default-fallback-image-if-no-image/)
Jetpack starts by looking for a Featured Image. If you didn’t define any, we will look for slideshows and galleries, and then for any images that may be attached to the post. If we don’t find any image attached to that post, we’ll look for single images you may have inserted in the post. If you’ve inserted an image that is hosted on another site, we can use it too.
However, sometimes you may not have added any image to your post.
In that case , we can set default image using the following code.
```
function wpse_203094_custom_image( $media, $post_id, $args ) {
if ( $media ) {
return $media;
} else {
$permalink = get_permalink( $post_id );
$url = 'YOUR_CUSTOM_DEFAULT_IMAGE_URL' ;
return array( array(
'type' => 'image',
'from' => 'custom_fallback',
'src' => esc_url( $url ),
'href' => $permalink,
) );
}
}
add_filter( 'jetpack_images_get_images', 'wpse_203094_custom_image', 10, 3 );
```
Or you can use filter to change the default one.
```
function wpse_203094_jetpack_default_image() {
return 'YOUR_IMAGE_URL';
}
add_filter( 'jetpack_open_graph_image_default', 'wpse_203094_jetpack_default_image' );
```
Or you can disable them entirely using:
```
add_filter( 'jetpack_enable_open_graph', '__return_false' );
```
Note
====
As **@cjbj** pointed out that some plugins like `Yoast SEO` can override open graph tags. The above filters/code works only for `Jetpack` assuming that no other plugins are overriding them.
Update
------
>
> Is there any solution, that would allow me to block og:image tag only for favicon
>
>
>
Yes there is , we can use [**`jetpack_images_get_images`**](https://github.com/Automattic/jetpack/blob/4.0.3/class.jetpack-post-images.php/#L496) filter.If we take a look at [**`jetpack_og_get_image`**](https://github.com/Automattic/jetpack/blob/4.0.3/functions.opengraph.php/#L340) src we can find that it adds core site icon like this
```
// Third fall back, Core Site Icon. Added in WP 4.3.
if ( empty( $image ) && ( function_exists( 'has_site_icon') && has_site_icon() ) ) {
$image['src'] = get_site_icon_url( 512 );
$image['width'] = '512';
$image['height'] = '512';
}
```
And finally defaults to blank image like this
```
// Finally fall back, blank image
if ( empty( $image ) ) {
/**
* Filter the default Open Graph Image tag, used when no Image can be found in a post.
*
* @since 3.0.0
*
* @param string $str Default Image URL.
*/
$image['src'] = apply_filters( 'jetpack_open_graph_image_default', 'https://s0.wp.com/i/blank.jpg' );
}
```
So as to make Jetpack assume that it has already got an image and there is no need to use `site icon`, we need to set some image.This can be done using the following code.Place this in `functions.php` of the active theme.
```
function wpse_203094_no_site_icon( $media, $post_id, $args ) {
if ( $media ) {
return $media;
} else {
return array( array(
'src' => '' // here we are conning Jetpack, Hurray!
) );
}
}
add_filter( 'jetpack_images_get_images', 'wpse_203094_no_site_icon', 10, 3 );
```
|
203,099 |
<p>I'm building a Wordpress plugin in which I need to get the <strong>HOME page ID value</strong>.</p>
<p>Do you know how can I get it?</p>
<p>I know that we can get the current ID with <code>the_ID()</code> or <code>get_the_ID()</code> function, but I need specificly the <strong>HOME page ID value</strong>.</p>
<p>My plugin is located at the following directory path:</p>
<pre><code>wp-content/plugins/myPlugin/
</code></pre>
|
[
{
"answer_id": 203104,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<p>If by Home Page you mean the page designated as the Posts page, the ID is stored in the option <code>page_for_posts</code>. If the value is 0, there is no designated home page.</p>\n"
},
{
"answer_id": 203106,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 6,
"selected": true,
"text": "<p><code>$pageID = get_option('page_on_front');</code> should get you the Page ID of the page set at 'Front Page' in WordPress options.</p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203099",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77424/"
] |
I'm building a Wordpress plugin in which I need to get the **HOME page ID value**.
Do you know how can I get it?
I know that we can get the current ID with `the_ID()` or `get_the_ID()` function, but I need specificly the **HOME page ID value**.
My plugin is located at the following directory path:
```
wp-content/plugins/myPlugin/
```
|
`$pageID = get_option('page_on_front');` should get you the Page ID of the page set at 'Front Page' in WordPress options.
|
203,112 |
<p>Below code adds <code>My Page</code> button in Admin Menu. It will take you to your author page when you click on it. However, it also opens up new page(Empty page).</p>
<p>I want it to just take you to author page and do not open a new page in backend.
How do I achieve that? I also make this menu show up for all user roles(it only shows up on Admin role now)</p>
<p>I know my code is wrong. Please let me know if you have any suggestion to write it better.</p>
<pre><code>add_action( 'admin_menu', 'add_my_custom_menu' );
function add_my_custom_menu() {
//add an item to the menu
add_menu_page (
'My Page',
'My Page',
'manage_options',
'my-page',
'see_my_page_function',
'dashicons-controls-play',
'100'
);
}
function see_my_page_function() {
$current_user = wp_get_current_user();
?>
<script>
url = "<?php echo get_site_url().'/author/'.$current_user->user_login.'/'; ?>";
window.open(url, '_blank');
</script>
<?php
}
</code></pre>
|
[
{
"answer_id": 203104,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<p>If by Home Page you mean the page designated as the Posts page, the ID is stored in the option <code>page_for_posts</code>. If the value is 0, there is no designated home page.</p>\n"
},
{
"answer_id": 203106,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 6,
"selected": true,
"text": "<p><code>$pageID = get_option('page_on_front');</code> should get you the Page ID of the page set at 'Front Page' in WordPress options.</p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74171/"
] |
Below code adds `My Page` button in Admin Menu. It will take you to your author page when you click on it. However, it also opens up new page(Empty page).
I want it to just take you to author page and do not open a new page in backend.
How do I achieve that? I also make this menu show up for all user roles(it only shows up on Admin role now)
I know my code is wrong. Please let me know if you have any suggestion to write it better.
```
add_action( 'admin_menu', 'add_my_custom_menu' );
function add_my_custom_menu() {
//add an item to the menu
add_menu_page (
'My Page',
'My Page',
'manage_options',
'my-page',
'see_my_page_function',
'dashicons-controls-play',
'100'
);
}
function see_my_page_function() {
$current_user = wp_get_current_user();
?>
<script>
url = "<?php echo get_site_url().'/author/'.$current_user->user_login.'/'; ?>";
window.open(url, '_blank');
</script>
<?php
}
```
|
`$pageID = get_option('page_on_front');` should get you the Page ID of the page set at 'Front Page' in WordPress options.
|
203,114 |
<p>I'm using <code>get_next_post_link()</code> and <code>get_previous_post_link()</code> within the loop but the returned posts are not correct.</p>
<p><code>get_next_post_link()</code> shows the previous post and <code>get_previous_post_link()</code> gives the current post. Below the context of these links:</p>
<pre><code>$args['name'] = $postname;
$query = new WP_Query($args);
if($query->have_posts())
{
while ($query->have_posts())
{
$query->the_post();
$id = get_the_ID();
$title = get_the_title();
$content = get_the_content();
$nextpost = get_next_post_link('Next: %link');
$previouspost = get_previous_post_link('Prev: %link');
}
}
</code></pre>
|
[
{
"answer_id": 203118,
"author": "bart",
"author_id": 80625,
"author_profile": "https://wordpress.stackexchange.com/users/80625",
"pm_score": 0,
"selected": false,
"text": "<p>This has been solved by changing <code>Site Address (URL)</code> in <code>Settings > General</code> to the path that matches with the posts's path. I was pulling in posts from another location in my website that did not match with the original (default) path of the post.</p>\n"
},
{
"answer_id": 295291,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": -1,
"selected": false,
"text": "<p>I think you can not pass proper argument. Please check this link for reference : <a href=\"https://codex.wordpress.org/Function_Reference/get_next_posts_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_next_posts_link</a> </p>\n"
},
{
"answer_id": 375509,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 0,
"selected": false,
"text": "<pre><code>get_next_post_link();\nget_previous_post_link();\n</code></pre>\n<p>These work on single posts for navigation from one single post to another NOT pagination for archive pages unless you use <code>get_query_var( 'paged' )</code></p>\n"
}
] |
2015/09/18
|
[
"https://wordpress.stackexchange.com/questions/203114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80625/"
] |
I'm using `get_next_post_link()` and `get_previous_post_link()` within the loop but the returned posts are not correct.
`get_next_post_link()` shows the previous post and `get_previous_post_link()` gives the current post. Below the context of these links:
```
$args['name'] = $postname;
$query = new WP_Query($args);
if($query->have_posts())
{
while ($query->have_posts())
{
$query->the_post();
$id = get_the_ID();
$title = get_the_title();
$content = get_the_content();
$nextpost = get_next_post_link('Next: %link');
$previouspost = get_previous_post_link('Prev: %link');
}
}
```
|
This has been solved by changing `Site Address (URL)` in `Settings > General` to the path that matches with the posts's path. I was pulling in posts from another location in my website that did not match with the original (default) path of the post.
|
203,128 |
<p>So for previous and next posts I used this from wordpress codex</p>
<pre><code><div class="navigation">
<p>
<?php posts_nav_link('&#8734;','Go Forward In Time','Go Back in Time'); ?>
</p>
</div>
</code></pre>
<p>I want to change that.. in the wp-admin, I used on settings -> reading -> Blog pages show at most = 5 so I wanted to have a button to click on and load like 5 more posts, every time you click on the button and you are on the bottom of the page ... to give you an example cuz my english is not that good..</p>
<p><a href="https://instagram.com/menwithclass" rel="nofollow">https://instagram.com/menwithclass</a></p>
<p>at first you see the some posts and if you scroll down, you click on a button and it loads more posts..</p>
<p>is that somehow possible to load the posts on the same page?</p>
|
[
{
"answer_id": 221915,
"author": "adiian",
"author_id": 91353,
"author_profile": "https://wordpress.stackexchange.com/users/91353",
"pm_score": 1,
"selected": false,
"text": "<p>That is practically the only option, to disable the php error/warning logging. There are 2 options to do it and another one which is not so good: </p>\n\n<ul>\n<li>php.ini - in most of the hosting you can change php.ini(even in shared hosting) - .htaccess</li>\n<li>directly in php files(not recommended)</li>\n</ul>\n\n<p><a href=\"http://phphtml.info/how-to-fix-wordpress-internal-pathfull-path-disclosurefpd-issue/\" rel=\"nofollow\">http://phphtml.info/how-to-fix-wordpress-internal-pathfull-path-disclosurefpd-issue/</a></p>\n"
},
{
"answer_id": 228128,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": false,
"text": "<p>PHP files in the wp-includes directory should not be accessible from the outside, they should only be included by wordpress code. Therefor an easy fix to this is to use .htaccess rules to block access to *.php files that are under the wp-includes directory</p>\n"
},
{
"answer_id": 251089,
"author": "haz",
"author_id": 99009,
"author_profile": "https://wordpress.stackexchange.com/users/99009",
"pm_score": -1,
"selected": false,
"text": "<p><em>Theoretically,</em> what I'm about to tell you is dangerous and probably shouldn't be done, if you're doing things the \"proper Wordpress way\".</p>\n\n<p><em>Practically</em>, this works for our production environment.</p>\n\n<p>The file <code>rss-functions.php</code> is deprecated, and redirects to <code>rss.php</code>.</p>\n\n<p>The file <code>rss.php</code> has been deprecated since v3.0.0, and internal comments recommend you use SimplePie instead.</p>\n\n<p>So the file <code>rss-functions.php</code> can be safely deleted <strong>as long as</strong> you don't have an old, legacy installation, and if you have no plugins which depend on this file.</p>\n\n<p>Alternatively, comment out line 8 in that file.</p>\n\n<hr>\n\n<p>From a security standpoint, you should also definitely implement @MarkKaplun's suggestion above, as this file isn't intended to be hit directly by the browser.</p>\n\n<hr>\n\n<p>BTW, I agree with you that divulging the full path is a security risk; we keep out WEBROOT at a custom path for that reason.</p>\n"
},
{
"answer_id": 309805,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 0,
"selected": false,
"text": "<h3><strong>Display_errors</strong> should be disabled on a production website.</h3>\n<p>WP Scan accesses <code>wp-includes/rss-functions.php</code> directly, and this is it's source code, as of WordPress 4.9.7:</p>\n<pre><code><?php\n/**\n * Deprecated. Use rss.php instead.\n *\n * @package WordPress\n */\n_deprecated_file( basename(__FILE__), '2.1.0', WPINC . '/rss.php' );\nrequire_once( ABSPATH . WPINC . '/rss.php' );\n</code></pre>\n<p>When it is accessed directly, <code>_deprecated_file()</code> function does not exist, so it throws a fatal error.</p>\n<p>The solution is to disable <code>display_errors</code> on a server level. If your PHP run under mod_apache, you can do it by adding this line to your main .htaccess file:</p>\n<pre><code>php_flag display_errors off\n</code></pre>\n<p>If you use PHP-FPM, you will probably have override php.ini in your local public_html folder.</p>\n<h3>Also, WordPress is aware of that:</h3>\n<p><a href=\"https://make.wordpress.org/core/handbook/testing/reporting-security-vulnerabilities/#why-are-there-path-disclosures-when-directly-loading-certain-files\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/handbook/testing/reporting-security-vulnerabilities/#why-are-there-path-disclosures-when-directly-loading-certain-files</a></p>\n"
}
] |
2015/09/19
|
[
"https://wordpress.stackexchange.com/questions/203128",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78209/"
] |
So for previous and next posts I used this from wordpress codex
```
<div class="navigation">
<p>
<?php posts_nav_link('∞','Go Forward In Time','Go Back in Time'); ?>
</p>
</div>
```
I want to change that.. in the wp-admin, I used on settings -> reading -> Blog pages show at most = 5 so I wanted to have a button to click on and load like 5 more posts, every time you click on the button and you are on the bottom of the page ... to give you an example cuz my english is not that good..
<https://instagram.com/menwithclass>
at first you see the some posts and if you scroll down, you click on a button and it loads more posts..
is that somehow possible to load the posts on the same page?
|
PHP files in the wp-includes directory should not be accessible from the outside, they should only be included by wordpress code. Therefor an easy fix to this is to use .htaccess rules to block access to \*.php files that are under the wp-includes directory
|
203,144 |
<p>I think I have a great idea to make my site load faster in mobile: <em>"don't load the custom fonts in small screens"</em></p>
<p>I know how to style/change the font used depending on screen size with media queries and css.
What I don't know is how to prevent the custom fonts from loading in small screens.
I use google fonts and I enqueue them in functions.php, but I'm open to your workarounds. </p>
<p>Btw, this how to do it, <a href="https://css-tricks.com/preventing-the-performance-hit-from-custom-fonts/" rel="nofollow">when using @font</a></p>
|
[
{
"answer_id": 203148,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress has <a href=\"https://codex.wordpress.org/Function_Reference/wp_is_mobile\" rel=\"nofollow\"><code>wp_is_mobile()</code></a> function to detect mobile and handheld devices. You can use that to define your enqueue function to load fonts conditionally.</p>\n\n<p>You can enqueue fonts for non mobile devices like this.</p>\n\n<pre><code>function my_enqueue_function() {\n\n if ( !wp_is_mobile() ) {\n\n wp_enqueue_style( 'gfonts', 'http://fonts.googleapis.com/css?family=Arbutus+Slab', false, NULL, 'all' );\n\n }\n\n}\nadd_action( 'wp_enqueue_scripts', 'my_enqueue_function' );\n</code></pre>\n"
},
{
"answer_id": 203149,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 0,
"selected": false,
"text": "<p>I found this (partial?) solution:</p>\n\n<p>Use wp_is_mobile() when you enqueue your fonts, like this:</p>\n\n<pre><code>function my_scripts() {\n // Load if not mobile\n if ( ! wp_is_mobile() ) {\n wp_enqueue_style( 'my-google-fonts', 'https://fonts.googleapis.com/css?family=Nicefont:400,500' );\n }\n // your other scripts that you enqueue...\n }\n add_action( 'wp_enqueue_scripts', 'my_scripts' );\n</code></pre>\n\n<p>references:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_is_mobile\" rel=\"nofollow noreferrer\">codex</a> and <a href=\"https://wordpress.stackexchange.com/questions/166086/dont-load-scripts-if-on-mobile-tablet\">other question</a></p>\n\n<p>There is also this <a href=\"https://github.com/scottsweb/mobble\" rel=\"nofollow noreferrer\">plug-in</a>, but I think it is overkill for my requirements.</p>\n"
}
] |
2015/09/19
|
[
"https://wordpress.stackexchange.com/questions/203144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
I think I have a great idea to make my site load faster in mobile: *"don't load the custom fonts in small screens"*
I know how to style/change the font used depending on screen size with media queries and css.
What I don't know is how to prevent the custom fonts from loading in small screens.
I use google fonts and I enqueue them in functions.php, but I'm open to your workarounds.
Btw, this how to do it, [when using @font](https://css-tricks.com/preventing-the-performance-hit-from-custom-fonts/)
|
WordPress has [`wp_is_mobile()`](https://codex.wordpress.org/Function_Reference/wp_is_mobile) function to detect mobile and handheld devices. You can use that to define your enqueue function to load fonts conditionally.
You can enqueue fonts for non mobile devices like this.
```
function my_enqueue_function() {
if ( !wp_is_mobile() ) {
wp_enqueue_style( 'gfonts', 'http://fonts.googleapis.com/css?family=Arbutus+Slab', false, NULL, 'all' );
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
```
|
203,208 |
<p>I would like to change the image sizes for "medium" and "large". </p>
<p>I did change the sizes in Settings > Media </p>
<p><a href="https://i.stack.imgur.com/yD7ro.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yD7ro.png" alt="enter image description here"></a></p>
<p>This however does not seem to have any effect on the settings I see when I edit or insert an image:</p>
<p><a href="https://i.stack.imgur.com/q5eZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q5eZY.png" alt="enter image description here"></a></p>
<p>I did empty cache and reset the browser.</p>
<p>I also changed the theme's settings for the custom image size and content_width accordingly – but this does not have any influence on what options are displayed under <em>Image Details</em>.</p>
<pre><code>add_image_size('full-width', 1600, 0, false);
if ( ! isset( $content_width ) ) $content_width = 1600;
</code></pre>
<p>Now I'm stuck – would appreciate any pointer… Thanks!</p>
<p>PS: I know there are plugins like <a href="https://wordpress.org/plugins/simple-image-sizes/" rel="nofollow noreferrer">Simple Image Sizes</a> that could be handy – but I would like to try to do this 'the right way' (if that makes any sence).</p>
|
[
{
"answer_id": 203210,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>Solved: The new / custom sizes are only available for new images… </p>\n"
},
{
"answer_id": 203216,
"author": "cameronjonesweb",
"author_id": 65582,
"author_profile": "https://wordpress.stackexchange.com/users/65582",
"pm_score": 2,
"selected": true,
"text": "<p>Your image sizes need to be regenerated, as for the images to have different sizes they need to be cropped from the original and written to an actual file, whereas the settings only updates the settings, so will only affect future uploads. The <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">Regenerate Thumbnails</a> plugin can help with fixing this. The plugin allows you to regenerate the image sizes for all images or any number of specific individual images.</p>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26059/"
] |
I would like to change the image sizes for "medium" and "large".
I did change the sizes in Settings > Media
[](https://i.stack.imgur.com/yD7ro.png)
This however does not seem to have any effect on the settings I see when I edit or insert an image:
[](https://i.stack.imgur.com/q5eZY.png)
I did empty cache and reset the browser.
I also changed the theme's settings for the custom image size and content\_width accordingly – but this does not have any influence on what options are displayed under *Image Details*.
```
add_image_size('full-width', 1600, 0, false);
if ( ! isset( $content_width ) ) $content_width = 1600;
```
Now I'm stuck – would appreciate any pointer… Thanks!
PS: I know there are plugins like [Simple Image Sizes](https://wordpress.org/plugins/simple-image-sizes/) that could be handy – but I would like to try to do this 'the right way' (if that makes any sence).
|
Your image sizes need to be regenerated, as for the images to have different sizes they need to be cropped from the original and written to an actual file, whereas the settings only updates the settings, so will only affect future uploads. The [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) plugin can help with fixing this. The plugin allows you to regenerate the image sizes for all images or any number of specific individual images.
|
203,209 |
<p>I am submitting my theme to WordPress.org. To make it compatible with WordPress 4.1 and greater, I replaced <code>wptitle()</code> tag with <code>add_theme_support( 'title-tag' )</code> but now the error has changed to following:</p>
<pre><code>REQUIRED: The <title> tags can only contain a call to wp_title(). Use the wp_title filter to modify the output
</code></pre>
<p>Here is a snippet from my header code:</p>
<pre><code><head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php add_theme_support( 'title-tag' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<?php wp_head(); ?>
</head>
</code></pre>
<p>I have read <a href="https://github.com/Otto42/theme-check/issues/10" rel="nofollow noreferrer">this</a> Github discussion and <a href="https://stackoverflow.com/questions/29794433/wp-head-add-a-second-title-tag">this</a> StackOverflow question to solve my problem.</p>
|
[
{
"answer_id": 203215,
"author": "Caspar",
"author_id": 27191,
"author_profile": "https://wordpress.stackexchange.com/users/27191",
"pm_score": 2,
"selected": false,
"text": "<p><code>add_theme_support( 'title-tag' )</code> doesn't belong in your header template. It belongs in your <code>functions.php</code> file. Usually, it's best to wrap it in it's own function and hook it to <code>after_setup_theme</code> in order to allow plugins and child themes to override it later if they need to. So...</p>\n\n<pre><code>function wpse_add_title_support() {\n add_theme_support( 'title-tag' );\n}\nadd_action ( 'after_setup_theme', 'wpse_add_title_support' );\n</code></pre>\n\n<p>Once you have declared title support, you can remove the <code><title></code> tag from <code>header.php</code> altogether and WP will handle putting it in.</p>\n"
},
{
"answer_id": 331182,
"author": "Alamgir Badsha",
"author_id": 162824,
"author_profile": "https://wordpress.stackexchange.com/users/162824",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this way:</p>\n\n<pre><code><title><?php wp_title( '|', true, 'right' ); ?></title>\n</code></pre>\n\n<p>and write this into after_setup_theme function <code>add_theme_support( 'title-tag' );</code></p>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I am submitting my theme to WordPress.org. To make it compatible with WordPress 4.1 and greater, I replaced `wptitle()` tag with `add_theme_support( 'title-tag' )` but now the error has changed to following:
```
REQUIRED: The <title> tags can only contain a call to wp_title(). Use the wp_title filter to modify the output
```
Here is a snippet from my header code:
```
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php add_theme_support( 'title-tag' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<?php wp_head(); ?>
</head>
```
I have read [this](https://github.com/Otto42/theme-check/issues/10) Github discussion and [this](https://stackoverflow.com/questions/29794433/wp-head-add-a-second-title-tag) StackOverflow question to solve my problem.
|
`add_theme_support( 'title-tag' )` doesn't belong in your header template. It belongs in your `functions.php` file. Usually, it's best to wrap it in it's own function and hook it to `after_setup_theme` in order to allow plugins and child themes to override it later if they need to. So...
```
function wpse_add_title_support() {
add_theme_support( 'title-tag' );
}
add_action ( 'after_setup_theme', 'wpse_add_title_support' );
```
Once you have declared title support, you can remove the `<title>` tag from `header.php` altogether and WP will handle putting it in.
|
203,223 |
<p>I am using the following code to display media files on a custom static page. Files display properly but pagination is <strong>not</strong> working. How can I solve this issue?</p>
<p>Following code shows the media files:</p>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'attachment',
'posts_per_page' => '10',
'paged' => $paged,
/* 'numberposts' => -1, */
'post_status' => null,
'author' => $current_user->ID,
'post_parent' => $post->ID,
/* 'caller_get_posts' => 1, */
);
// The Query
$query = new WP_Query( $args );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<tr><td><a href="' . wp_get_attachment_url( $attachment->ID ) .
'" rel="shadowbox" title="' . $attachment->post_excerpt . '">';
echo ($attachment->_wp_attached_file);
echo '</a>
</td>';
</tr>';
}
}
</code></pre>
<p>Added following to <code>functions.php</code>:</p>
<pre><code>if ( ! function_exists( 'my_pagination' ) ) :
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'prev_next' => True,
'prev_text' => __( '« Previous' ),
'next_text' => __( 'Next »' ),
'type' => 'plain',
'add_args' => False,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
) );
}
endif;
</code></pre>
<p>Page number or pagination not working, calling the function in my static page like so:</p>
<pre><code>echo my_pagination( $args );
</code></pre>
|
[
{
"answer_id": 203248,
"author": "Asadullah",
"author_id": 30852,
"author_profile": "https://wordpress.stackexchange.com/users/30852",
"pm_score": 0,
"selected": false,
"text": "<p>Pagination is always based on main query that is in your case is static page and has only one page hence no pagination. </p>\n\n<p>You need to do a simple hack as provided in <a href=\"https://wordpress.stackexchange.com/a/120408\">this answer</a></p>\n"
},
{
"answer_id": 204858,
"author": "Ubaid Rehman",
"author_id": 81560,
"author_profile": "https://wordpress.stackexchange.com/users/81560",
"pm_score": 1,
"selected": false,
"text": "<p>Dear I have wasted my week on this problem, basically when you select static page as your home page in setting->reading of wordpress the complete behavior of listing things are changed, basically static pages are never meant for pagination the fact is when you call the $paged variable it will always return zero even if you define its value to 1 the pagination will just refresh your page, because its a page not a .php valid file page is already a taxonomy function that is called in index.php of main wordpress the function will always return same thing no matter what you do,</p>\n\n<p>The work around make a index.php file copy all the content from that static page to it and then replace it with your index.php and select latest post in setting->reading of wordpress </p>\n\n<p>Now if you really don't want to mess with it, but still want to have the pagination then you need to write a small code of yours for pagination</p>\n\n<p>basically home.com/page/2 will never work but home.com/?page=2 will always work but changing the permalink structure will change it for every thing so we will create a pagination function that will call next page with home.com/?page=2 structure url</p>\n\n<pre><code>/* ------------------------------------------------------------------*/\n/* PAGINATION */\n/* ------------------------------------------------------------------*/\n\n//paste this where the pagination must appear\n\nglobal $wp_query;\n$total = $wp_query->max_num_pages;\n// only bother with the rest if we have more than 1 page!\nif ( $total > 1 ) {\n // get the current page\n if ( !$current_page = get_query_var('paged') )\n $current_page = 1;\n // structure of \"format\" depends on whether we're using pretty permalinks\n if( get_option('permalink_structure') ) {\n $format = '?paged=%#%';\n }\n echo paginate_links(array(\n 'base' => get_pagenum_link(1) . '%_%',\n 'format' => $format,\n 'current' => $current_page,\n 'total' => $total,\n 'mid_size' => 4,\n 'type' => 'list'\n ));\n}\n</code></pre>\n\n<p>if you include this code where this rather than the current pagination you will see it working :)</p>\n"
},
{
"answer_id": 223297,
"author": "satinder ghai",
"author_id": 92150,
"author_profile": "https://wordpress.stackexchange.com/users/92150",
"pm_score": 0,
"selected": false,
"text": "<p>// Its working on home page \nset the \"paged\" parameter (use 'page' if the query is on a static front page)</p>\n\n<pre><code><?php\n$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';\n$args = array (\n 'nopaging' => false,\n 'paged' => $paged,\n 'posts_per_page' => '1',\n 'post_type' => 'post',\n 'category__not_in' => array(97),\n);\n\n// The Query\n$query = new WP_Query( $args );\nprint_r($query);\n$total_pages = $query->max_num_pages;\n\n\nif ($total_pages > 1){\n\n $current_page = max(1, get_query_var('paged'));\n echo '<div class=\"navigation\">';\n\n echo paginate_links(array(\n 'base' => get_pagenum_link(1) . '%_%',\n 'format' => '?paged=%#%',\n 'current' => $current_page,\n 'total' => $total_pages,\n 'type' => 'list',\n 'prev_text' => __('Previous Posts'),\n 'next_text' => __('More Posts'),\n ));\n echo '</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 266249,
"author": "Prafulla Kumar Sahu",
"author_id": 81273,
"author_profile": "https://wordpress.stackexchange.com/users/81273",
"pm_score": 0,
"selected": false,
"text": "<p>The question is quite older but still my answer will be helpful, I hope, as I was in this condition for last 2/3 days and solved it now. The simple fact is</p>\n\n<blockquote>\n <p>Static front pages uses get_query_var( 'page' ) and not get_query_var(\n 'paged' ).</p>\n</blockquote>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203223",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80689/"
] |
I am using the following code to display media files on a custom static page. Files display properly but pagination is **not** working. How can I solve this issue?
Following code shows the media files:
```
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'attachment',
'posts_per_page' => '10',
'paged' => $paged,
/* 'numberposts' => -1, */
'post_status' => null,
'author' => $current_user->ID,
'post_parent' => $post->ID,
/* 'caller_get_posts' => 1, */
);
// The Query
$query = new WP_Query( $args );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<tr><td><a href="' . wp_get_attachment_url( $attachment->ID ) .
'" rel="shadowbox" title="' . $attachment->post_excerpt . '">';
echo ($attachment->_wp_attached_file);
echo '</a>
</td>';
</tr>';
}
}
```
Added following to `functions.php`:
```
if ( ! function_exists( 'my_pagination' ) ) :
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $wp_query->max_num_pages,
'prev_next' => True,
'prev_text' => __( '« Previous' ),
'next_text' => __( 'Next »' ),
'type' => 'plain',
'add_args' => False,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
) );
}
endif;
```
Page number or pagination not working, calling the function in my static page like so:
```
echo my_pagination( $args );
```
|
Dear I have wasted my week on this problem, basically when you select static page as your home page in setting->reading of wordpress the complete behavior of listing things are changed, basically static pages are never meant for pagination the fact is when you call the $paged variable it will always return zero even if you define its value to 1 the pagination will just refresh your page, because its a page not a .php valid file page is already a taxonomy function that is called in index.php of main wordpress the function will always return same thing no matter what you do,
The work around make a index.php file copy all the content from that static page to it and then replace it with your index.php and select latest post in setting->reading of wordpress
Now if you really don't want to mess with it, but still want to have the pagination then you need to write a small code of yours for pagination
basically home.com/page/2 will never work but home.com/?page=2 will always work but changing the permalink structure will change it for every thing so we will create a pagination function that will call next page with home.com/?page=2 structure url
```
/* ------------------------------------------------------------------*/
/* PAGINATION */
/* ------------------------------------------------------------------*/
//paste this where the pagination must appear
global $wp_query;
$total = $wp_query->max_num_pages;
// only bother with the rest if we have more than 1 page!
if ( $total > 1 ) {
// get the current page
if ( !$current_page = get_query_var('paged') )
$current_page = 1;
// structure of "format" depends on whether we're using pretty permalinks
if( get_option('permalink_structure') ) {
$format = '?paged=%#%';
}
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => $format,
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'list'
));
}
```
if you include this code where this rather than the current pagination you will see it working :)
|
203,224 |
<p>There seems to be a ton of information on checking a <code>meta_key</code> against an array of <code>meta_values</code>, but I want to do the opposite. </p>
<p>I have a site with projects, and press reviews. When the client adds a review, they have a custom field (ACF) to select the project it relates to from a list. </p>
<p>I am now trying to display all press reviews that relate to a certain project, together on a page. I have the project ID, and use a query with $args to select the press reviews I want.</p>
<p>My current <code>$args</code>: </p>
<pre><code>$args = array(
'post_type' => 'pressreview',
'order' => DESC,
'meta_query' => array(
array(
'key' => 'belongs_to_project',
'value' => $projectID,
'compare' => 'LIKE'
)
)
);
</code></pre>
<p>The problem is, that custom field '<code>belongs_to_project</code>' returns an array with IDs. One press review can be about multiple projects, so I let the client pick multiple projects from the list in that field. A typical array will be like this: </p>
<pre><code>Array ( [0] => 210 [1] => 202 ).
</code></pre>
<p>What I want to do, is check whether the <code>$projectID</code> is in that array. </p>
<p>In the current setup, it sort of works: if the client selected 202 and 210 from the list, and the <code>$projectID</code> is <code>210</code>, the press review is shown. However, if the <code>$projectID = 20</code>, we get press reviews for projects <code>201</code>, <code>202</code>, <code>203</code>, etc. (since those numbers include '<code>20</code>', which is how <code>LIKE</code> works)</p>
<p>Is there any way I can tell this query to only check for 'whole' numbers? So that "2" would only show reviews for project <code>2</code>, and not for <code>201</code>, <code>202</code>, or any other numbers that have a 2 in them? </p>
<p>I've seen there is a <code>REGEXP</code> option to use instead of <code>LIKE</code>, but I can't find out how to use it in a way that it checks for only 'whole numbers'.</p>
<p>I've also tried '<code>IN</code>', but that doesn't work at all here.</p>
<p>One thing that I thought of, but don't know whether it's possible at all, is to use something like:</p>
<pre><code>'key' => 'belongs_to_project[$i]'
</code></pre>
<p>with some kind of loop through the key values, so that <code>$projectID</code> could be checked with <code>'='</code> instead of <code>LIKE</code> against each of the values in the array of the custom field.
I've no idea if there's any such option and how it should be written.</p>
<p>Hope my explanation is clear enough, please let me know if I need to explain better.</p>
|
[
{
"answer_id": 203235,
"author": "Khaled Sadek",
"author_id": 75122,
"author_profile": "https://wordpress.stackexchange.com/users/75122",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that you should use <code>IN</code> at <code>compare</code>\nbut you said this's not working.\nand I notice something (please forgive me if this's a mistake ):\nyou write example for array</p>\n\n<pre><code>Array ( [0] => 210 [1] => 202 ).\n</code></pre>\n\n<p>this mean the value in array is <code>NUMERIC</code> and the Default type is 'CHAR'.\nso you can try </p>\n\n<pre><code>$args = array(\n 'post_type' => 'pressreview',\n 'order' => DESC,\n 'meta_query' => array(\n array(\n 'key' => 'belongs_to_project',\n 'value' => $projectID,\n 'compare' => 'IN',\n 'type' => 'NUMERIC'\n )\n )\n);\n</code></pre>\n"
},
{
"answer_id": 203437,
"author": "Els",
"author_id": 80687,
"author_profile": "https://wordpress.stackexchange.com/users/80687",
"pm_score": 4,
"selected": true,
"text": "<p>The solution was that I need to compare the literal value of <code>$projectID</code>, so that <code>LIKE</code> compares an exact string instead of just numbers. To make <code>$projectID</code> literal, it needs to be wrapped in quotes.</p>\n\n<p>So, I changed this line:</p>\n\n<p><code>'value' => $projectID,</code></p>\n\n<p>to:</p>\n\n<p><code>'value' => '\"'.$projectID.'\"',</code></p>\n\n<p>Which solves the problem. </p>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203224",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80687/"
] |
There seems to be a ton of information on checking a `meta_key` against an array of `meta_values`, but I want to do the opposite.
I have a site with projects, and press reviews. When the client adds a review, they have a custom field (ACF) to select the project it relates to from a list.
I am now trying to display all press reviews that relate to a certain project, together on a page. I have the project ID, and use a query with $args to select the press reviews I want.
My current `$args`:
```
$args = array(
'post_type' => 'pressreview',
'order' => DESC,
'meta_query' => array(
array(
'key' => 'belongs_to_project',
'value' => $projectID,
'compare' => 'LIKE'
)
)
);
```
The problem is, that custom field '`belongs_to_project`' returns an array with IDs. One press review can be about multiple projects, so I let the client pick multiple projects from the list in that field. A typical array will be like this:
```
Array ( [0] => 210 [1] => 202 ).
```
What I want to do, is check whether the `$projectID` is in that array.
In the current setup, it sort of works: if the client selected 202 and 210 from the list, and the `$projectID` is `210`, the press review is shown. However, if the `$projectID = 20`, we get press reviews for projects `201`, `202`, `203`, etc. (since those numbers include '`20`', which is how `LIKE` works)
Is there any way I can tell this query to only check for 'whole' numbers? So that "2" would only show reviews for project `2`, and not for `201`, `202`, or any other numbers that have a 2 in them?
I've seen there is a `REGEXP` option to use instead of `LIKE`, but I can't find out how to use it in a way that it checks for only 'whole numbers'.
I've also tried '`IN`', but that doesn't work at all here.
One thing that I thought of, but don't know whether it's possible at all, is to use something like:
```
'key' => 'belongs_to_project[$i]'
```
with some kind of loop through the key values, so that `$projectID` could be checked with `'='` instead of `LIKE` against each of the values in the array of the custom field.
I've no idea if there's any such option and how it should be written.
Hope my explanation is clear enough, please let me know if I need to explain better.
|
The solution was that I need to compare the literal value of `$projectID`, so that `LIKE` compares an exact string instead of just numbers. To make `$projectID` literal, it needs to be wrapped in quotes.
So, I changed this line:
`'value' => $projectID,`
to:
`'value' => '"'.$projectID.'"',`
Which solves the problem.
|
203,229 |
<p>I have this plugin I created that has a custom post type and a template file that renders the posts.
I want to be able to render the template in any page using a short code. So what I created was this piece of code which I am sure is wrong and would totally appreciate it if someone could answer how I am supposed to render the template </p>
<pre><code>function display_timeline(){
ob_start();
locate_template(plugin_dir_path( __FILE__ ) . '/timelines.php', true, false);
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
add_shortcode( 'wptimeline_display', 'display_timeline' );
</code></pre>
<p>Also, the template and the plugin functions are both in the same directory. </p>
|
[
{
"answer_id": 203230,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 0,
"selected": false,
"text": "<p>Please try using <code>get_template_part('timelines');</code> instead of <code>locate_template(plugin_dir_path( __FILE__ ) . '/timelines.php', true, false);</code> I just given it a try and it works fine. Let me know if this solves your problem.</p>\n"
},
{
"answer_id": 203234,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://wpseek.com/function/locate_template/\" rel=\"nofollow\"><code>locate_template()</code></a> only look for a specific template in themes, not in plugins, so your function wil never work. This also goes for <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\"><code>get_template_part()</code></a> which is in essence just a wrapper function for <code>locate_template()</code>.</p>\n\n<p>You will need to use funtions like <a href=\"http://php.net/manual/en/function.file-exists.php\" rel=\"nofollow\"><code>file_exists()</code></a> to check whether or not the required template exists and then use something like <a href=\"http://php.net/manual/en/function.include.php\" rel=\"nofollow\"><code>include()</code></a> to load your template. You can use the above to write your own function like <code>locate_template()</code>, this is at least what I will do, and have a fallback to lacate a template in themes should the template not exist in the plugin.</p>\n\n<p>Just a note, always always first check if a value/template/condition exists before doing something with it. This will avoid unnecessary bugs and issues should a failure occur. Also, have something in place like returning false, adding a redirect, exiting etc etc to safely handle your code should you have a failure</p>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48389/"
] |
I have this plugin I created that has a custom post type and a template file that renders the posts.
I want to be able to render the template in any page using a short code. So what I created was this piece of code which I am sure is wrong and would totally appreciate it if someone could answer how I am supposed to render the template
```
function display_timeline(){
ob_start();
locate_template(plugin_dir_path( __FILE__ ) . '/timelines.php', true, false);
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
add_shortcode( 'wptimeline_display', 'display_timeline' );
```
Also, the template and the plugin functions are both in the same directory.
|
[`locate_template()`](http://wpseek.com/function/locate_template/) only look for a specific template in themes, not in plugins, so your function wil never work. This also goes for [`get_template_part()`](https://developer.wordpress.org/reference/functions/get_template_part/) which is in essence just a wrapper function for `locate_template()`.
You will need to use funtions like [`file_exists()`](http://php.net/manual/en/function.file-exists.php) to check whether or not the required template exists and then use something like [`include()`](http://php.net/manual/en/function.include.php) to load your template. You can use the above to write your own function like `locate_template()`, this is at least what I will do, and have a fallback to lacate a template in themes should the template not exist in the plugin.
Just a note, always always first check if a value/template/condition exists before doing something with it. This will avoid unnecessary bugs and issues should a failure occur. Also, have something in place like returning false, adding a redirect, exiting etc etc to safely handle your code should you have a failure
|
203,239 |
<p>Ive got a CPT and in my CPT's argument I am calling the taxonomy <code>post_tag</code>. When I create a <code>tag.php</code> file it doesn't show any of the posts for said tag. My <code>tag.php</code>:</p>
<pre><code><?php get_header(); ?>
<section class="row">
<div class="col-md-7">
<p>Tag: <?php single_tag_title(); ?></p>
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile;
else: ?>
<p>not working</p>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
</section>
<?php get_footer(); ?>
</code></pre>
<p>In my research I ran across "<a href="https://wordpress.stackexchange.com/questions/28145/tag-php-doesnt-work-with-tags-on-a-custom-post-type-post">tag.php doesn't work with tags on a custom post type post?</a>" but I am using what I thought was the default for tags <code>post_tag</code>. When I was referencing <code>WP_Query()</code> Tag Parameters it doesn't show how to take into consideration for the tag clicked. When I search for tag.php I get <a href="https://codex.wordpress.org/Tag_Templates" rel="nofollow noreferrer">Tag Templates</a> and it doesn't show any examples that take into consideration all tags. What is the proper way to write a <code>WP_Query()</code> for all posts pertaining to the tag? I did run across <a href="https://codex.wordpress.org/Function_Reference/wp_get_post_tags" rel="nofollow noreferrer"><code>wp_get_post_tags()</code></a> after some research and reading "<a href="https://stackoverflow.com/questions/22911300/wordpress-get-related-pages-tag-based-wp-get-post-tags">Wordpress get related pages (tag based) - wp_get_post_tags</a>" but I'm not understanding the rewrite for tag.php and the codex has no examples. So how can I properly write my tag.php to return all posts for the clicked tag?</p>
|
[
{
"answer_id": 203241,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 4,
"selected": true,
"text": "<p>I figured it out thanks to <a href=\"https://wordpress.stackexchange.com/questions/203239/tag-php-not-displaying-posts-with-the-tag#comment295054_203239\">Pieter's comment</a>:</p>\n\n<p>In <code>functions.php</code> I added:</p>\n\n<pre><code>function tag_filter($query) {\n if ( !is_admin() && $query->is_main_query() ) {\n if ($query->is_tag) {\n $query->set('post_type', array( 'custom_post_type', ));\n }\n }\n}\nadd_action('pre_get_posts','tag_filter');\n</code></pre>\n"
},
{
"answer_id": 330543,
"author": "lozov",
"author_id": 162429,
"author_profile": "https://wordpress.stackexchange.com/users/162429",
"pm_score": 2,
"selected": false,
"text": "<p>This worked perfectly for me. I also wanted to include other post types, so I added:</p>\n\n<pre><code>$query->set('post_type', array( 'custom_post_type', 'post', 'page' ));\n</code></pre>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] |
Ive got a CPT and in my CPT's argument I am calling the taxonomy `post_tag`. When I create a `tag.php` file it doesn't show any of the posts for said tag. My `tag.php`:
```
<?php get_header(); ?>
<section class="row">
<div class="col-md-7">
<p>Tag: <?php single_tag_title(); ?></p>
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile;
else: ?>
<p>not working</p>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
</section>
<?php get_footer(); ?>
```
In my research I ran across "[tag.php doesn't work with tags on a custom post type post?](https://wordpress.stackexchange.com/questions/28145/tag-php-doesnt-work-with-tags-on-a-custom-post-type-post)" but I am using what I thought was the default for tags `post_tag`. When I was referencing `WP_Query()` Tag Parameters it doesn't show how to take into consideration for the tag clicked. When I search for tag.php I get [Tag Templates](https://codex.wordpress.org/Tag_Templates) and it doesn't show any examples that take into consideration all tags. What is the proper way to write a `WP_Query()` for all posts pertaining to the tag? I did run across [`wp_get_post_tags()`](https://codex.wordpress.org/Function_Reference/wp_get_post_tags) after some research and reading "[Wordpress get related pages (tag based) - wp\_get\_post\_tags](https://stackoverflow.com/questions/22911300/wordpress-get-related-pages-tag-based-wp-get-post-tags)" but I'm not understanding the rewrite for tag.php and the codex has no examples. So how can I properly write my tag.php to return all posts for the clicked tag?
|
I figured it out thanks to [Pieter's comment](https://wordpress.stackexchange.com/questions/203239/tag-php-not-displaying-posts-with-the-tag#comment295054_203239):
In `functions.php` I added:
```
function tag_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_tag) {
$query->set('post_type', array( 'custom_post_type', ));
}
}
}
add_action('pre_get_posts','tag_filter');
```
|
203,240 |
<p>I need to sort my products by rating in a wp_query loop:</p>
<p>this is my code:</p>
<pre><code>switch($ordering){
case 'default':
$meta_key = '';
$order = 'asc';
$orderby = 'menu_order title';
break;
case 'popularity':
$meta_key = '';
$order = 'desc';
$orderby = 'total_sales';
break;
case 'low_to_high':
$meta_key = '_price';
$order = 'asc';
$orderby = 'meta_value_num';
break;
case 'high_to_low':
$meta_key = '_price';
$order = 'desc';
$orderby = 'meta_value_num';
break;
case 'newness':
$meta_key = '';
$order = 'desc';
$orderby = 'date';
break;
case 'rating':
$meta_key = '';
$order = 'desc';
$orderby = 'rating';
break;
}
$args_products_sorting = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => $orderby,
'order' => $order,
'meta_key' => $meta_key
);
</code></pre>
<p>Where is the error ?</p>
<p>If i set in url <code>?orderby=rating</code> it works correctly.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 219219,
"author": "Shamar Kellman",
"author_id": 88986,
"author_profile": "https://wordpress.stackexchange.com/users/88986",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <code>'orderby' => 'meta_value_num'</code> and <code>'meta_key' => 'rating'</code> as specified by the WordPress Codec. Using <code>meta_value_num</code> with the assumption your ratings are numeric values </p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\">Orderby Parameters</a></p>\n"
},
{
"answer_id": 219255,
"author": "borisdiakur",
"author_id": 86420,
"author_profile": "https://wordpress.stackexchange.com/users/86420",
"pm_score": 3,
"selected": false,
"text": "<p>Seems like there are a lot of meta keys you can order by (<a href=\"https://wedevs.com/support/topic/meta-keys-for-attributes/#post-4742\" rel=\"nofollow\">here</a> is a list I’ve found). However I couldn’t find anything rating related. I searched for <code>rating</code> in the WooCommerce source code and found this line: <a href=\"https://github.com/woothemes/woocommerce/blob/master/includes/abstracts/abstract-wc-product.php#L1087\" rel=\"nofollow\">includes/abstracts/abstract-wc-product.php#L1087</a></p>\n\n<p>So here is what finally worked for me in the context of using the WooCommerce PHP REST API client:</p>\n\n<pre><code>function getProducts(WP_REST_Request $request) {\n global $wc_api_client;\n\n $category = $request->get_param('category');\n // $filters = $request->get_param('filters');\n $orderby = $request->get_param('orderby');\n\n $args = null;\n\n $wc_query = new WC_Query();\n switch ( $orderby ) {\n case 'date':\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'date',\n 'filter[order]' => 'DESC'\n );\n break;\n case 'price':\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'meta_value_num',\n 'filter[order]' => 'ASC',\n 'filter[orderby_meta_key]' => '_price'\n );\n break;\n case 'price-desc':\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'meta_value_num',\n 'filter[order]' => 'DESC',\n 'filter[orderby_meta_key]' => '_price'\n );\n break;\n case 'popularity':\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'meta_value_num',\n 'filter[order]' => 'DESC',\n 'filter[orderby_meta_key]' => 'total_sales'\n );\n break;\n case 'rating':\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'meta_value_num',\n 'filter[order]' => 'DESC',\n 'filter[orderby_meta_key]' => '_wc_average_rating'\n );\n break;\n default:\n $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category\n );\n }\n\n try {\n $raw = $wc_api_client->products->get('', $args);\n return $raw['products'];\n } catch (Exception $e) {\n return new WP_Error('no_products', 'Couldn’t find any products', array('status' => 404));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 248757,
"author": "user2462948",
"author_id": 108629,
"author_profile": "https://wordpress.stackexchange.com/users/108629",
"pm_score": 1,
"selected": false,
"text": "<p>I used something like that and it works</p>\n\n<pre>\nswitch ($order_by){\n case 'price':\n $args['orderby'] = 'meta_value_num';\n $args['meta_key'] = '_price';\n $args['order'] = 'asc';\n break;\n\n case 'price-desc':\n $args['orderby'] = 'meta_value_num';\n $args['meta_key'] = '_price';\n $args['order'] = 'desc';\n break;\n\n case 'rating':\n $args['orderby'] = 'meta_value_num';\n $args['meta_key'] = '_wc_average_rating';\n $args['order'] = 'desc';\n break;\n\n case 'popularity':\n $args['orderby'] = 'meta_value_num';\n $args['meta_key'] = 'total_sales';\n $args['order'] = 'desc';\n break;\n }\n</pre>\n"
},
{
"answer_id": 339440,
"author": "Iris Nguyen",
"author_id": 168200,
"author_profile": "https://wordpress.stackexchange.com/users/168200",
"pm_score": 0,
"selected": false,
"text": "<p>Try this . Use WC_Shortcode_Products to generate the wc loop with sort parameters were used at default wc shop page</p>\n\n<pre><code>for($i=1;$i<=$num;$i++){\n $atts = array_merge(array(\n 'columns' => $columns,\n 'orderby' => $order_by,\n 'order' => $sort_by,//rating , population , price high to low ,....\n 'rows' => $rows,\n 'page' => $i,\n ));\n $shortcode = new WC_Shortcode_Products($atts, 'recent_products');\n echo $shortcode->get_content();\n}\n</code></pre>\n"
},
{
"answer_id": 377537,
"author": "softnwords",
"author_id": 81815,
"author_profile": "https://wordpress.stackexchange.com/users/81815",
"pm_score": 0,
"selected": false,
"text": "<p>use this codefor arg</p>\n<pre><code>$args = array(\n 'post_type' => 'product',\n 'orderby' => $args = array(\n 'filter[limit]' => 6,\n 'filter[category]' => $category,\n 'filter[orderby]' => 'meta_value_num',\n 'filter[order]' => 'DESC',\n 'filter[orderby_meta_key]' => '_wc_average_rating'\n ),\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'id',\n 'terms' => $category\n )\n ),\n 'posts_per_page' => $product_number\n );\n</code></pre>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18072/"
] |
I need to sort my products by rating in a wp\_query loop:
this is my code:
```
switch($ordering){
case 'default':
$meta_key = '';
$order = 'asc';
$orderby = 'menu_order title';
break;
case 'popularity':
$meta_key = '';
$order = 'desc';
$orderby = 'total_sales';
break;
case 'low_to_high':
$meta_key = '_price';
$order = 'asc';
$orderby = 'meta_value_num';
break;
case 'high_to_low':
$meta_key = '_price';
$order = 'desc';
$orderby = 'meta_value_num';
break;
case 'newness':
$meta_key = '';
$order = 'desc';
$orderby = 'date';
break;
case 'rating':
$meta_key = '';
$order = 'desc';
$orderby = 'rating';
break;
}
$args_products_sorting = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => $orderby,
'order' => $order,
'meta_key' => $meta_key
);
```
Where is the error ?
If i set in url `?orderby=rating` it works correctly.
Thanks.
|
You should use `'orderby' => 'meta_value_num'` and `'meta_key' => 'rating'` as specified by the WordPress Codec. Using `meta_value_num` with the assumption your ratings are numeric values
Reference: [Orderby Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters)
|
203,252 |
<p>I have just started playing with the WP REST API and found that when querying posts that there is a limit of 10 post per page unless specified. What I would like to know if is is possible to return the total number of post in a category though meta data or something similar?</p>
|
[
{
"answer_id": 236877,
"author": "Sdghasemi",
"author_id": 101489,
"author_profile": "https://wordpress.stackexchange.com/users/101489",
"pm_score": -1,
"selected": false,
"text": "<p>A bit late to the party but in case someone trying to find a solution to do such thing with WP REST API even v2, I have to say <strong>YOU CANNOT</strong>.\nI've spent hours on searching through Google and WordPress or the library official docs but unfortunately came up with nothing.</p>\n\n<p>So I tried getting posts with increasing page number until the returned <strong>JSON array length</strong> becomes <strong>0</strong> which means there's <strong>no more page with posts</strong> on the category, and stopped increasing the page number.</p>\n\n<p>Hope it helps somebody.</p>\n"
},
{
"answer_id": 236895,
"author": "Jesús Franco",
"author_id": 16301,
"author_profile": "https://wordpress.stackexchange.com/users/16301",
"pm_score": 2,
"selected": false,
"text": "<p>To just know the number of posts in a category, its endpoint returns that number straightforward, in example:</p>\n\n<pre><code>curl http://wired.com/wp-json/wp/v2/categories/24\n</code></pre>\n\n<p>In the resource returned, the <code>count</code> field says: 486</p>\n\n<p>Which is the same number the metadata says about the total number of posts, if you request the posts in that category, rather than the category itself:</p>\n\n<pre><code>curl -I http://wired.com/wp-json/wp/v2/posts?categories=24\n</code></pre>\n\n<p>You can read the header <code>X-WP-Total: 486</code>.</p>\n\n<p>REST API of WordPress follows best practices in use today for APIs, among others, return metadata about a request in the headers, plus links to traverse the collection if it is possible.</p>\n\n<p>There is no need to wait for an array of posts of length === 0 in order to know there are no more pages of posts.</p>\n\n<p>Actually, the rest API return in headers, metadata about the number of pages and total of posts available to this same endpoint/filter.</p>\n\n<p>For example, take the API of wired.com:</p>\n\n<pre><code>curl -I http://wired.com/wp-json/wp/v2/posts/\n</code></pre>\n\n<p>It returns three headers relevant to this question:</p>\n\n<pre><code>Link: <http://www.wired.com/wp-json/wp/v2/posts?page=2>; rel=\"next\"\nX-WP-TotalPages: 18067\nX-WP-Total: 180664\n</code></pre>\n\n<p>As you can see, the results are consistent enough to know if you need to retrieve more posts or you have reached the end of the listing. You have X-WP-Total showing total of resources for this endpoint, X-WP-TotalPages showing number of pages with the same number of posts (default is 10, but you can request more with query argument <code>per_page</code>).</p>\n\n<p>And the Link header gives you even more information which you can use to traverse without even storing the total number of posts before requesting more.</p>\n\n<p>For example: <code>$ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=18067</code>\nGives you this Link header:</p>\n\n<pre><code>Link: <http://www.wired.com/wp-json/wp/v2/posts?page=18066>; rel=\"prev\"\n</code></pre>\n\n<p>(No <code>next</code> link, just as first page has not <code>prev</code> link).</p>\n\n<p>And an intermediate page: <code>$ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=2</code>\nGives you next and prev links:</p>\n\n<pre><code>Link: <http://www.wired.com/wp-json/wp/v2/posts?page=1>; rel=\"prev\", <http://www.wired.com/wp-json/wp/v2/posts?page=3>; rel=\"next\"\n</code></pre>\n\n<p>I'd suspect the number of posts REST API can return is more related to server capabilities, since I've being able to return <code>per_page=100</code> without any trouble.</p>\n"
}
] |
2015/09/20
|
[
"https://wordpress.stackexchange.com/questions/203252",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80701/"
] |
I have just started playing with the WP REST API and found that when querying posts that there is a limit of 10 post per page unless specified. What I would like to know if is is possible to return the total number of post in a category though meta data or something similar?
|
To just know the number of posts in a category, its endpoint returns that number straightforward, in example:
```
curl http://wired.com/wp-json/wp/v2/categories/24
```
In the resource returned, the `count` field says: 486
Which is the same number the metadata says about the total number of posts, if you request the posts in that category, rather than the category itself:
```
curl -I http://wired.com/wp-json/wp/v2/posts?categories=24
```
You can read the header `X-WP-Total: 486`.
REST API of WordPress follows best practices in use today for APIs, among others, return metadata about a request in the headers, plus links to traverse the collection if it is possible.
There is no need to wait for an array of posts of length === 0 in order to know there are no more pages of posts.
Actually, the rest API return in headers, metadata about the number of pages and total of posts available to this same endpoint/filter.
For example, take the API of wired.com:
```
curl -I http://wired.com/wp-json/wp/v2/posts/
```
It returns three headers relevant to this question:
```
Link: <http://www.wired.com/wp-json/wp/v2/posts?page=2>; rel="next"
X-WP-TotalPages: 18067
X-WP-Total: 180664
```
As you can see, the results are consistent enough to know if you need to retrieve more posts or you have reached the end of the listing. You have X-WP-Total showing total of resources for this endpoint, X-WP-TotalPages showing number of pages with the same number of posts (default is 10, but you can request more with query argument `per_page`).
And the Link header gives you even more information which you can use to traverse without even storing the total number of posts before requesting more.
For example: `$ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=18067`
Gives you this Link header:
```
Link: <http://www.wired.com/wp-json/wp/v2/posts?page=18066>; rel="prev"
```
(No `next` link, just as first page has not `prev` link).
And an intermediate page: `$ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=2`
Gives you next and prev links:
```
Link: <http://www.wired.com/wp-json/wp/v2/posts?page=1>; rel="prev", <http://www.wired.com/wp-json/wp/v2/posts?page=3>; rel="next"
```
I'd suspect the number of posts REST API can return is more related to server capabilities, since I've being able to return `per_page=100` without any trouble.
|
203,270 |
<p>I am trying to add css code into head tag. the css style is from shortcodes. title text from shortcode and title color / font size.. etc.
This is an example.</p>
<pre><code><html>
<head>
<?php wp_head(); ?>
.................. (some style, js) ..................
/* I want to put all of css styles into head tag from into body tags */
</head>
<body>
<?php
//shortcode css from user custom option
add_action( 'wp_head', 'iulia_example' );
function iulia_example() {
echo '<style type="text/css">
.sc_title {color:#fff; font-weight:600;}
</style>';
}
?>
<!-- shortcode -->
<div class="sc_wrap">
<h1 class="sc_title">Hello This is the title</h1>
</div>
</body>
</html>
</code></pre>
<p>I want to use wp_head hook to place css style in head tag. however it's not working.
Is there another way to add the css code in head? wp_head is not working in "body tag" and it gets the custom css variables from shortcode and it's in BODY.</p>
<p>Thank you,</p>
|
[
{
"answer_id": 203272,
"author": "Ahmar Ali",
"author_id": 45901,
"author_profile": "https://wordpress.stackexchange.com/users/45901",
"pm_score": 0,
"selected": false,
"text": "<p>Create a new folder in your theme for CSS. Put your custom styling in a separate file and save it in css folder. Let's say you named your file custom.css</p>\n\n<p>Here is how you add it . In <code>Functions.php</code>:</p>\n\n<pre><code>wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/css/custom.css', null, null, 'all'); \n</code></pre>\n\n<p>Ahmar</p>\n"
},
{
"answer_id": 203275,
"author": "Alessandro Benoit",
"author_id": 16637,
"author_profile": "https://wordpress.stackexchange.com/users/16637",
"pm_score": 2,
"selected": false,
"text": "<p>It's not working because you're calling add_action after the actual action is fired. If you move the action declaration before wp_head() it will work:</p>\n\n<pre><code><html>\n <head>\n <?php\n add_action( 'wp_head', function () { \n echo '<style type=\"text/css\">.sc_title {color:#fff; font-weight:600;}</style>';\n });\n ?>\n <?php wp_head(); ?>\n</code></pre>\n\n<p>There's no easy way to add some code to the head from the body tag as that code would be evaluated later. If you really need to do so you can play with <a href=\"http://php.net/manual/en/function.ob-start.php\" rel=\"nofollow\">output buffering</a> (evaluate first the body template and buffer it) but I can't see why you should. </p>\n\n<p><strong>In reply to the latests comments:</strong></p>\n\n<p>If I've understood right what you want to achieve is to have some css being put in the head when a shortcode is add in the content, right? In that case you might add a check in the header for the content of the post. If it match a given shortcode then you output your styles. You can add something like the following to your functions.php, but it's kind of an hack:</p>\n\n<pre><code>add_action('wp_head', function () {\n global $post;\n if ($post) {\n setup_postdata($post);\n $content = get_the_content();\n preg_match('/\\[my_shortcode\\]/', $content, $matches);\n if ($matches) {\n echo '<style>.some_style { font-weight:800; }</style>';\n }\n }\n});\n</code></pre>\n"
}
] |
2015/09/21
|
[
"https://wordpress.stackexchange.com/questions/203270",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34463/"
] |
I am trying to add css code into head tag. the css style is from shortcodes. title text from shortcode and title color / font size.. etc.
This is an example.
```
<html>
<head>
<?php wp_head(); ?>
.................. (some style, js) ..................
/* I want to put all of css styles into head tag from into body tags */
</head>
<body>
<?php
//shortcode css from user custom option
add_action( 'wp_head', 'iulia_example' );
function iulia_example() {
echo '<style type="text/css">
.sc_title {color:#fff; font-weight:600;}
</style>';
}
?>
<!-- shortcode -->
<div class="sc_wrap">
<h1 class="sc_title">Hello This is the title</h1>
</div>
</body>
</html>
```
I want to use wp\_head hook to place css style in head tag. however it's not working.
Is there another way to add the css code in head? wp\_head is not working in "body tag" and it gets the custom css variables from shortcode and it's in BODY.
Thank you,
|
It's not working because you're calling add\_action after the actual action is fired. If you move the action declaration before wp\_head() it will work:
```
<html>
<head>
<?php
add_action( 'wp_head', function () {
echo '<style type="text/css">.sc_title {color:#fff; font-weight:600;}</style>';
});
?>
<?php wp_head(); ?>
```
There's no easy way to add some code to the head from the body tag as that code would be evaluated later. If you really need to do so you can play with [output buffering](http://php.net/manual/en/function.ob-start.php) (evaluate first the body template and buffer it) but I can't see why you should.
**In reply to the latests comments:**
If I've understood right what you want to achieve is to have some css being put in the head when a shortcode is add in the content, right? In that case you might add a check in the header for the content of the post. If it match a given shortcode then you output your styles. You can add something like the following to your functions.php, but it's kind of an hack:
```
add_action('wp_head', function () {
global $post;
if ($post) {
setup_postdata($post);
$content = get_the_content();
preg_match('/\[my_shortcode\]/', $content, $matches);
if ($matches) {
echo '<style>.some_style { font-weight:800; }</style>';
}
}
});
```
|
203,277 |
<p>In my site I've does some coding based on the category like <code>in_category('featured')</code> do something. Now, this is only applicable to posts only. Also the posts which is associated with <code>featured</code> category is also associated with other category too. As it is only associated with <code>featured</code> category to show up with special design thats it.</p>
<p>Now I know that this question has been discussed before here many time, but not exactly what I'm looking for. So before downgrading this question, red it properly.</p>
<p>Here in this post <a href="https://wordpress.stackexchange.com/questions/31553/is-there-a-quick-way-to-hide-category-from-everywhere">is there a quick way to hide category from everywhere?</a> the following function is provided to exclude some categories, but I don't want to exclude it I just want to hide it.</p>
<pre><code>add_action('pre_get_posts', 'wpa_31553' );
function wpa_31553( $wp_query ) {
//$wp_query is passed by reference. we don't need to return anything. whatever changes made inside this function will automatically effect the global variable
$excluded = array(272); //made it an array in case you need to exclude more than one
// only exclude on the front end
if( !is_admin() ) {
$wp_query->set('category__not_in', $excluded);
}
}
</code></pre>
<p>As an example let's say a post is associated with <code>featured</code> category and also associated with <code>Work</code> category. Now as <code>featured</code> is alphabetically comes first the breadcrumb (using Yoast SEO Breadcrumb) will show <code>featured</code> as category name also the post meta (shown below the posts) will show up both category names i.e. <code>featured</code> and <code>work</code>.</p>
<p>That is why I want to hide the <code>featured</code> category completely so that no front end user will ever have idea that <code>featured</code> category exists. It wont show up in breadcrumb, post meta, post category list, no where. It will remain hidden but in the backend code it will still work when I try to do specific with those posts inside <code>featured</code> category using <code>in_category('featured')</code>.</p>
<p>Does anyone know how to obtain this category hiding (not excluding) feature.</p>
|
[
{
"answer_id": 203281,
"author": "Alessandro Benoit",
"author_id": 16637,
"author_profile": "https://wordpress.stackexchange.com/users/16637",
"pm_score": 2,
"selected": true,
"text": "<p>Replace all the call to in_category('featured') with the custom function inCategory('featured'), declare it on your functions.php:</p>\n\n<pre><code>/**\n * @param string $category\n *\n * @return bool\n */\nfunction inCategory($category)\n{\n global $wpdb, $post;\n\n if ( ! $post) {\n return false;\n }\n\n $query = $wpdb->prepare(\"SELECT COUNT(t.term_id)\n FROM $wpdb->terms AS t\n INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id\n INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id\n WHERE tr.object_id = %d\n AND tt.taxonomy = '%s'\n AND t.slug = '%s'\n \", $post->ID, 'category', $category);\n\n return (bool) $wpdb->get_var($query);\n}\n</code></pre>\n\n<p>The add the following filters:</p>\n\n<pre><code>/**\n * @param array $terms\n *\n * @return array\n */\nfunction remove_featured_category_from_frontend(array $terms)\n{\n if ( ! is_admin()) {\n $terms = array_filter($terms, function ($term) {\n if ($term->taxonomy === 'category') {\n return $term->slug !== 'featured';\n }\n\n return true;\n });\n }\n\n return $terms;\n}\n\nadd_filter('get_terms', 'remove_featured_category_from_frontend');\nadd_filter('get_object_terms', 'remove_featured_category_from_frontend');\n</code></pre>\n\n<p>Give it a try and let me know.</p>\n"
},
{
"answer_id": 382891,
"author": "Mehmet Cemil",
"author_id": 197464,
"author_profile": "https://wordpress.stackexchange.com/users/197464",
"pm_score": 0,
"selected": false,
"text": "<p>this is the easiest method</p>\n<pre><code> if($category->name == 'genel') continue;\n</code></pre>\n"
}
] |
2015/09/21
|
[
"https://wordpress.stackexchange.com/questions/203277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50584/"
] |
In my site I've does some coding based on the category like `in_category('featured')` do something. Now, this is only applicable to posts only. Also the posts which is associated with `featured` category is also associated with other category too. As it is only associated with `featured` category to show up with special design thats it.
Now I know that this question has been discussed before here many time, but not exactly what I'm looking for. So before downgrading this question, red it properly.
Here in this post [is there a quick way to hide category from everywhere?](https://wordpress.stackexchange.com/questions/31553/is-there-a-quick-way-to-hide-category-from-everywhere) the following function is provided to exclude some categories, but I don't want to exclude it I just want to hide it.
```
add_action('pre_get_posts', 'wpa_31553' );
function wpa_31553( $wp_query ) {
//$wp_query is passed by reference. we don't need to return anything. whatever changes made inside this function will automatically effect the global variable
$excluded = array(272); //made it an array in case you need to exclude more than one
// only exclude on the front end
if( !is_admin() ) {
$wp_query->set('category__not_in', $excluded);
}
}
```
As an example let's say a post is associated with `featured` category and also associated with `Work` category. Now as `featured` is alphabetically comes first the breadcrumb (using Yoast SEO Breadcrumb) will show `featured` as category name also the post meta (shown below the posts) will show up both category names i.e. `featured` and `work`.
That is why I want to hide the `featured` category completely so that no front end user will ever have idea that `featured` category exists. It wont show up in breadcrumb, post meta, post category list, no where. It will remain hidden but in the backend code it will still work when I try to do specific with those posts inside `featured` category using `in_category('featured')`.
Does anyone know how to obtain this category hiding (not excluding) feature.
|
Replace all the call to in\_category('featured') with the custom function inCategory('featured'), declare it on your functions.php:
```
/**
* @param string $category
*
* @return bool
*/
function inCategory($category)
{
global $wpdb, $post;
if ( ! $post) {
return false;
}
$query = $wpdb->prepare("SELECT COUNT(t.term_id)
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id
INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tr.object_id = %d
AND tt.taxonomy = '%s'
AND t.slug = '%s'
", $post->ID, 'category', $category);
return (bool) $wpdb->get_var($query);
}
```
The add the following filters:
```
/**
* @param array $terms
*
* @return array
*/
function remove_featured_category_from_frontend(array $terms)
{
if ( ! is_admin()) {
$terms = array_filter($terms, function ($term) {
if ($term->taxonomy === 'category') {
return $term->slug !== 'featured';
}
return true;
});
}
return $terms;
}
add_filter('get_terms', 'remove_featured_category_from_frontend');
add_filter('get_object_terms', 'remove_featured_category_from_frontend');
```
Give it a try and let me know.
|
203,279 |
<p>Change title separator.</p>
<p>I'm working with the underscores starter theme. I want to make a small change to the title. Change the separator from
"Post title | site name" to "Post title - site name"</p>
<p>The simple way of doing this was to put </p>
<pre><code> <title><?php wp_title('-', true, 'right' ); ?><?php bloginfo( 'name' ); ?></title>
</code></pre>
<p>in the header.
But now I read that with the introduction of <code>add_theme_support( 'title-tag' );</code> one <a href="https://make.wordpress.org/themes/2015/08/25/title-tag-support-now-required/" rel="noreferrer">should not use</a> the <code><title></code> markup in the header. </p>
<p>So is there a simple way to change the separator in the title? </p>
<p>Why this question is different from other similar questions:
This is really about best practice, since the introduction of <code>add_theme_support( 'title-tag' );</code> and how to use and modify it, since we are no longer supposed to use the <code><title></code> tag in the header.</p>
<p>[ I really hope that I don't have to write 8 lines of code to make such a small change.
If I decide to finally use the <code><title></code> tag as a more straightforward solution, should I comment out/remove the <code>add_theme_support( 'title-tag' );</code> from functions.php? ]</p>
|
[
{
"answer_id": 203285,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 5,
"selected": true,
"text": "<h2>UPDATE for WordPress 4.4</h2>\n\n<p>Since WordPress 4.4 the <code>wp_title</code> filter doesn't work because <code>wp_title()</code> function is not used in core anymore. That function was marked as deprecated, then reinstated until new notice but <a href=\"https://make.wordpress.org/core/2015/10/20/document-title-in-4-4/\">theme authors are discouraged from using it</a>. Because of that, <code>wp_title</code> filter still will work if you continue using <code>wp_title()</code> function directly in your theme but it is not recommended.</p>\n\n<p>There are new filters to customize the document title when theme support for <code>title-tag</code> is enabled:</p>\n\n<ol>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\"><code>pre_get_document_title</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\"><code>document_title_parts</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/document_title_separator/\"><code>document_title_separator</code></a>.</li>\n</ol>\n\n<p>As you only want to customize the separator, you can use <code>document_title_separator</code> as follow:</p>\n\n<pre><code>add_filter( 'document_title_separator', 'cyb_document_title_separator' );\nfunction cyb_document_title_separator( $sep ) {\n\n $sep = \"-\";\n\n return $sep;\n\n}\n</code></pre>\n\n<h2>Previous answer</h2>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title\"><code>wp_title</code> filter</a> to customize the <code><title></code> tag.</p>\n\n<pre><code>add_filter( 'wp_title', 'customize_title_tag', 10, 3 );\nfunction customize_title_tag( $title, $sep, $seplocation ) {\n\n\n // Customize $title here.\n // Example taken from https://generatepress.com/forums/topic/title-tag-separator/\n $title = str_replace( '|', '-', $title );\n\n return $title;\n\n}\n</code></pre>\n\n<p>A more complex example of how to use this filter (taken from TwentyTwelve theme):</p>\n\n<pre><code>function twentytwelve_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() )\n return $title;\n\n // Add the site name.\n $title .= get_bloginfo( 'name' );\n\n // Add the site description for the home/front page.\n $site_description = get_bloginfo( 'description', 'display' );\n if ( $site_description && ( is_home() || is_front_page() ) )\n $title = \"$title $sep $site_description\";\n\n // Add a page number if necessary.\n if ( $paged >= 2 || $page >= 2 )\n $title = \"$title $sep \" . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) );\n\n return $title;\n}\nadd_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 369137,
"author": "SnnSnn",
"author_id": 165241,
"author_profile": "https://wordpress.stackexchange.com/users/165241",
"pm_score": 1,
"selected": false,
"text": "<p>How document title is generated has changed since Wordpress v4.4.0. Now <code>wp_get_document_title</code> dictates how title is generated:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Displays title tag with content.\n *\n * @ignore\n * @since 4.1.0\n * @since 4.4.0 Improved title output replaced `wp_title()`.\n * @access private\n */\nfunction _wp_render_title_tag() {\n if ( ! current_theme_supports( 'title-tag' ) ) {\n return;\n }\n\n echo '<title>' . wp_get_document_title() . '</title>' . "\\n";\n}\n</code></pre>\n<p>Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wp_get_document_title() {\n /**\n * Filters the document title before it is generated.\n *\n * Passing a non-empty value will short-circuit wp_get_document_title(),\n * returning that value instead.\n *\n * @since 4.4.0\n *\n * @param string $title The document title. Default empty string.\n */\n $title = apply_filters( 'pre_get_document_title', '' );\n if ( ! empty( $title ) ) {\n return $title;\n }\n // --- snipped ---\n /**\n * Filters the separator for the document title.\n *\n * @since 4.4.0\n *\n * @param string $sep Document title separator. Default '-'.\n */\n $sep = apply_filters( 'document_title_separator', '-' );\n\n /**\n * Filters the parts of the document title.\n *\n * @since 4.4.0\n *\n * @param array $title {\n * The document title parts.\n *\n * @type string $title Title of the viewed page.\n * @type string $page Optional. Page number if paginated.\n * @type string $tagline Optional. Site description when on home page.\n * @type string $site Optional. Site title when not on home page.\n * }\n */\n $title = apply_filters( 'document_title_parts', $title );\n // --- snipped ---\n return $title;\n}\n</code></pre>\n<p>So here are two ways you can do it.</p>\n<p>First one uses <code>pre_get_document_title</code> filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_document_title( $title ) {\n return 'Here is the new title';\n}\nadd_filter( 'pre_get_document_title', 'custom_document_title', 10 );\n</code></pre>\n<p>Second way uses <code>document_title_separator</code> and <code>document_title_parts</code> hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like <code>single_term_title</code> or <code>post_type_archive_title</code> depending on the page and about to be outputted:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Custom function should return a string\nfunction custom_seperator( $sep ) {\n return '>';\n}\nadd_filter( 'document_title_separator', 'custom_seperator', 10 );\n\n// Custom function should return an array\nfunction custom_html_title( $title ) {\n return array(\n 'title' => 'Custom Title',\n 'site' => 'Custom Site'\n );\n}\nadd_filter( 'document_title_parts', 'custom_html_title', 10 );\n</code></pre>\n"
}
] |
2015/09/21
|
[
"https://wordpress.stackexchange.com/questions/203279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
Change title separator.
I'm working with the underscores starter theme. I want to make a small change to the title. Change the separator from
"Post title | site name" to "Post title - site name"
The simple way of doing this was to put
```
<title><?php wp_title('-', true, 'right' ); ?><?php bloginfo( 'name' ); ?></title>
```
in the header.
But now I read that with the introduction of `add_theme_support( 'title-tag' );` one [should not use](https://make.wordpress.org/themes/2015/08/25/title-tag-support-now-required/) the `<title>` markup in the header.
So is there a simple way to change the separator in the title?
Why this question is different from other similar questions:
This is really about best practice, since the introduction of `add_theme_support( 'title-tag' );` and how to use and modify it, since we are no longer supposed to use the `<title>` tag in the header.
[ I really hope that I don't have to write 8 lines of code to make such a small change.
If I decide to finally use the `<title>` tag as a more straightforward solution, should I comment out/remove the `add_theme_support( 'title-tag' );` from functions.php? ]
|
UPDATE for WordPress 4.4
------------------------
Since WordPress 4.4 the `wp_title` filter doesn't work because `wp_title()` function is not used in core anymore. That function was marked as deprecated, then reinstated until new notice but [theme authors are discouraged from using it](https://make.wordpress.org/core/2015/10/20/document-title-in-4-4/). Because of that, `wp_title` filter still will work if you continue using `wp_title()` function directly in your theme but it is not recommended.
There are new filters to customize the document title when theme support for `title-tag` is enabled:
1. [`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/)
2. [`document_title_parts`](https://developer.wordpress.org/reference/hooks/document_title_parts/)
3. [`document_title_separator`](https://developer.wordpress.org/reference/hooks/document_title_separator/).
As you only want to customize the separator, you can use `document_title_separator` as follow:
```
add_filter( 'document_title_separator', 'cyb_document_title_separator' );
function cyb_document_title_separator( $sep ) {
$sep = "-";
return $sep;
}
```
Previous answer
---------------
You can use [`wp_title` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title) to customize the `<title>` tag.
```
add_filter( 'wp_title', 'customize_title_tag', 10, 3 );
function customize_title_tag( $title, $sep, $seplocation ) {
// Customize $title here.
// Example taken from https://generatepress.com/forums/topic/title-tag-separator/
$title = str_replace( '|', '-', $title );
return $title;
}
```
A more complex example of how to use this filter (taken from TwentyTwelve theme):
```
function twentytwelve_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() )
return $title;
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
// Add a page number if necessary.
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 );
```
|
203,352 |
<p>I am using <a href="https://github.com/WebDevStudios/CMB2" rel="nofollow">CMB2</a> for metabox on custom posts. I am adding a metabox by using code below:</p>
<pre><code>$cmb_demo->add_field( array(
'name' => __( 'Test Text', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'text',
'type' => 'text',
'show_on_cb' => 'show_this_field_if_true',
) );
</code></pre>
<p>I understand show_this_field_if_true will be a function that will return true or false. But, I want to make this as conditional with another field. This field will show if another field's value is true. </p>
<p>Here is an example that Don't show this field if it's not the front page template</p>
<pre><code>function show_this_field_if_true( $cmb ) {
if ( $cmb->object_id !== get_option( 'page_on_front' ) ) {
return false;
}
return true;
}
</code></pre>
<p>How can I make this conditional with a field? </p>
|
[
{
"answer_id": 220702,
"author": "Justin Sternberg",
"author_id": 45740,
"author_profile": "https://wordpress.stackexchange.com/users/45740",
"pm_score": 2,
"selected": false,
"text": "<p>You need to replace the <code>get_option</code> call with a call to <code>get_post_meta</code>:</p>\n\n<pre><code>function show_this_field_if_true( $cmb ) {\n // Check if other meta value exists\n if ( ! get_post_meta( $cmb->object_id, 'other_meta_key_to_check', 1 ) ) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Keep in mind, this will only work for the initial page-load and will not show the field until you update the <code>other_meta_key_to_check</code> value and save the page.</p>\n"
},
{
"answer_id": 353423,
"author": "Adil Elsaeed",
"author_id": 49202,
"author_profile": "https://wordpress.stackexchange.com/users/49202",
"pm_score": 1,
"selected": true,
"text": "<p>The best way to do this is by using JavaScript and there is a couple of CMB2 plugins let you do that easily:</p>\n\n<ol>\n<li><a href=\"https://github.com/jcchavezs/cmb2-conditionals\" rel=\"nofollow noreferrer\">CMB2 Conditional</a> </li>\n<li><a href=\"https://github.com/awran5/CMB2-conditional-logic\" rel=\"nofollow noreferrer\">CMB2 Conditional Logic</a></li>\n</ol>\n"
}
] |
2015/09/22
|
[
"https://wordpress.stackexchange.com/questions/203352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12198/"
] |
I am using [CMB2](https://github.com/WebDevStudios/CMB2) for metabox on custom posts. I am adding a metabox by using code below:
```
$cmb_demo->add_field( array(
'name' => __( 'Test Text', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'text',
'type' => 'text',
'show_on_cb' => 'show_this_field_if_true',
) );
```
I understand show\_this\_field\_if\_true will be a function that will return true or false. But, I want to make this as conditional with another field. This field will show if another field's value is true.
Here is an example that Don't show this field if it's not the front page template
```
function show_this_field_if_true( $cmb ) {
if ( $cmb->object_id !== get_option( 'page_on_front' ) ) {
return false;
}
return true;
}
```
How can I make this conditional with a field?
|
The best way to do this is by using JavaScript and there is a couple of CMB2 plugins let you do that easily:
1. [CMB2 Conditional](https://github.com/jcchavezs/cmb2-conditionals)
2. [CMB2 Conditional Logic](https://github.com/awran5/CMB2-conditional-logic)
|
203,406 |
<p>I have a <code>front-page.php</code> to create the index page template and a <code>page-blog.php</code> to create the blog template. My styles are added using <code>wp_enqueue_style</code> in my <code>functions.php</code>, but I'd like to use different items (css and js) on <code>page-blog.php</code>. Is it possible?</p>
|
[
{
"answer_id": 203407,
"author": "WordPress Mike",
"author_id": 33921,
"author_profile": "https://wordpress.stackexchange.com/users/33921",
"pm_score": 1,
"selected": false,
"text": "<p>You should use a conditional based on the page template. </p>\n\n<pre><code>if ( is_page_template( 'page-blog.php' ) ) {\n wp_enqueue_style( 'stylesheet_name' );\n wp_enqueue_script( 'script_name' );\n}\n</code></pre>\n"
},
{
"answer_id": 203408,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>When using hooks such as <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> you have access to <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">Conditional Tags</a>. This allows you to only enqueue certain things on certain pages, templates, taxonomies, etc.</p>\n\n<p>By default, WordPress accepts two template files as the natural blog:</p>\n\n<ol>\n<li><code>index.php</code></li>\n<li><code>home.php</code></li>\n</ol>\n\n<p>You can read more about this in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display\" rel=\"nofollow\">Template Hierarchy</a> post, while it does say \"Home\" this will only take the place of the homepage if <code>front-page.php</code> does not exist in your theme. What you have is a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#page\" rel=\"nofollow\">Page Template</a> as your \"Blog\" and <strong>not the standard</strong> you need to use <code>is_page()</code>:</p>\n\n<pre><code>/**\n * Enqueue Styles and Scripts\n */\nfunction theme_name_scripts() {\n if( is_page( 'blog' ) ) { // Only add this style onto the Blog page.\n wp_enqueue_style( 'style-name', get_stylesheet_uri() );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n</code></pre>\n"
}
] |
2015/09/22
|
[
"https://wordpress.stackexchange.com/questions/203406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78432/"
] |
I have a `front-page.php` to create the index page template and a `page-blog.php` to create the blog template. My styles are added using `wp_enqueue_style` in my `functions.php`, but I'd like to use different items (css and js) on `page-blog.php`. Is it possible?
|
When using hooks such as [`wp_enqueue_scripts`](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) you have access to [Conditional Tags](https://codex.wordpress.org/Conditional_Tags). This allows you to only enqueue certain things on certain pages, templates, taxonomies, etc.
By default, WordPress accepts two template files as the natural blog:
1. `index.php`
2. `home.php`
You can read more about this in the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display) post, while it does say "Home" this will only take the place of the homepage if `front-page.php` does not exist in your theme. What you have is a [Page Template](https://developer.wordpress.org/themes/basics/template-hierarchy/#page) as your "Blog" and **not the standard** you need to use `is_page()`:
```
/**
* Enqueue Styles and Scripts
*/
function theme_name_scripts() {
if( is_page( 'blog' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
}
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
```
|
203,434 |
<p>I want to be able to reference the theme directory in a page/post using php code. I don't know how to do this with WordPress but other CMS use something like a <code>path_to_home</code> php variable like </p>
<pre><code><img src="<?php path_to_home() . 'images/image.jpb'; ?>">
</code></pre>
<p>In WP I tried</p>
<pre><code><img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide">
</code></pre>
<p>but that doesn't work the same way or I need something different than <code>get_template_directory_uri()</code>.</p>
<p>BTW my output with this code is a literal</p>
<pre><code><img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide">
</code></pre>
|
[
{
"answer_id": 203407,
"author": "WordPress Mike",
"author_id": 33921,
"author_profile": "https://wordpress.stackexchange.com/users/33921",
"pm_score": 1,
"selected": false,
"text": "<p>You should use a conditional based on the page template. </p>\n\n<pre><code>if ( is_page_template( 'page-blog.php' ) ) {\n wp_enqueue_style( 'stylesheet_name' );\n wp_enqueue_script( 'script_name' );\n}\n</code></pre>\n"
},
{
"answer_id": 203408,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>When using hooks such as <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> you have access to <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">Conditional Tags</a>. This allows you to only enqueue certain things on certain pages, templates, taxonomies, etc.</p>\n\n<p>By default, WordPress accepts two template files as the natural blog:</p>\n\n<ol>\n<li><code>index.php</code></li>\n<li><code>home.php</code></li>\n</ol>\n\n<p>You can read more about this in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display\" rel=\"nofollow\">Template Hierarchy</a> post, while it does say \"Home\" this will only take the place of the homepage if <code>front-page.php</code> does not exist in your theme. What you have is a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#page\" rel=\"nofollow\">Page Template</a> as your \"Blog\" and <strong>not the standard</strong> you need to use <code>is_page()</code>:</p>\n\n<pre><code>/**\n * Enqueue Styles and Scripts\n */\nfunction theme_name_scripts() {\n if( is_page( 'blog' ) ) { // Only add this style onto the Blog page.\n wp_enqueue_style( 'style-name', get_stylesheet_uri() );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n</code></pre>\n"
}
] |
2015/09/22
|
[
"https://wordpress.stackexchange.com/questions/203434",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45709/"
] |
I want to be able to reference the theme directory in a page/post using php code. I don't know how to do this with WordPress but other CMS use something like a `path_to_home` php variable like
```
<img src="<?php path_to_home() . 'images/image.jpb'; ?>">
```
In WP I tried
```
<img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide">
```
but that doesn't work the same way or I need something different than `get_template_directory_uri()`.
BTW my output with this code is a literal
```
<img class="first-slide" src="<?php get_template_directory_uri() . '/images/landing-banner.png'; ?>" alt="First slide">
```
|
When using hooks such as [`wp_enqueue_scripts`](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) you have access to [Conditional Tags](https://codex.wordpress.org/Conditional_Tags). This allows you to only enqueue certain things on certain pages, templates, taxonomies, etc.
By default, WordPress accepts two template files as the natural blog:
1. `index.php`
2. `home.php`
You can read more about this in the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display) post, while it does say "Home" this will only take the place of the homepage if `front-page.php` does not exist in your theme. What you have is a [Page Template](https://developer.wordpress.org/themes/basics/template-hierarchy/#page) as your "Blog" and **not the standard** you need to use `is_page()`:
```
/**
* Enqueue Styles and Scripts
*/
function theme_name_scripts() {
if( is_page( 'blog' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
}
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
```
|
203,444 |
<p>Is there a way to count the number of posts / pages via the WordPress API?</p>
<p>I'm wanting to insert a post then check, using the API, that the count has gone up by 1.</p>
<p>I've looked at <a href="http://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.getPosts" rel="nofollow">http://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.getPosts</a> </p>
|
[
{
"answer_id": 223214,
"author": "Tim",
"author_id": 56882,
"author_profile": "https://wordpress.stackexchange.com/users/56882",
"pm_score": 3,
"selected": true,
"text": "<p>Assuming you are using Linux or OS X, the easiest way is probably to use wp-cli (if present in your WordPress installation) to return a list of all posts: </p>\n\n<pre><code>wp-cli post list\n</code></pre>\n\n<p>Then pipe it to the word count tool to get the number of lines: </p>\n\n<pre><code>wc -l\n</code></pre>\n\n<p>Finally, deduct one to take care of the header line which is not a post: </p>\n\n<pre><code>awk '{print $1-1}'\n</code></pre>\n\n<p>So, in one line: </p>\n\n<pre><code>wp-cli post list | wc -l | awk '{print $1-1}'\n</code></pre>\n"
},
{
"answer_id": 228722,
"author": "Justin",
"author_id": 95204,
"author_profile": "https://wordpress.stackexchange.com/users/95204",
"pm_score": 3,
"selected": false,
"text": "<p>With WP-CLI installed from <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">https://wp-cli.org/</a> you can retrieve the total post count by using:</p>\n\n<p><code>wp post list --format=count</code></p>\n\n<p><a href=\"https://wp-cli.org/commands/post/list/\" rel=\"nofollow noreferrer\">Full documentation for the POST LIST command</a></p>\n"
}
] |
2015/09/22
|
[
"https://wordpress.stackexchange.com/questions/203444",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48904/"
] |
Is there a way to count the number of posts / pages via the WordPress API?
I'm wanting to insert a post then check, using the API, that the count has gone up by 1.
I've looked at <http://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.getPosts>
|
Assuming you are using Linux or OS X, the easiest way is probably to use wp-cli (if present in your WordPress installation) to return a list of all posts:
```
wp-cli post list
```
Then pipe it to the word count tool to get the number of lines:
```
wc -l
```
Finally, deduct one to take care of the header line which is not a post:
```
awk '{print $1-1}'
```
So, in one line:
```
wp-cli post list | wc -l | awk '{print $1-1}'
```
|
203,487 |
<p>I was using the following: <code>get_home_path();</code> in my functions.php as referenced <a href="https://codex.wordpress.org/Function_Reference/get_home_path" rel="nofollow noreferrer">in the docs</a> – but I get the error:</p>
<pre><code>Call to undefined function get_home_path() in ...
</code></pre>
<p>I'd like to include a file using it. I noticed there is also the constant <code>ABSPATH</code>. Is there any reason I shouldn't just use <code>ABSPATH</code> as an alternative to <code>get_home_path()</code>?</p>
<h3>Edit</h3>
<p>I am using it as so (this is crazy simple) – in my functions.php file at the start of the file I have put:</p>
<pre><code>require_once( ABSPATH . 'vendor/autoload.php' );
</code></pre>
<p>If I put:</p>
<pre><code>$path = get_home_path();
require_once( $path . 'vendor/autoload.php' );
</code></pre>
<p>That's when it all goes wrong, with the generic error about the function not being available.</p>
|
[
{
"answer_id": 286097,
"author": "Steven",
"author_id": 13118,
"author_profile": "https://wordpress.stackexchange.com/users/13118",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps this issue is that <code>get_home_path()</code> can only be used in the admin?\nAs it says in small letters in <a href=\"https://codex.wordpress.org/Function_Reference/get_home_path\" rel=\"nofollow noreferrer\">the docs</a>:</p>\n\n<blockquote>\n <p>This is a backend function.</p>\n</blockquote>\n"
},
{
"answer_id": 326879,
"author": "DACrosby",
"author_id": 31367,
"author_profile": "https://wordpress.stackexchange.com/users/31367",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_home_path\" rel=\"nofollow noreferrer\"><code>get_home_path()</code> only works when WP admin scripts are loaded.</a></p>\n\n<p><code>ABSPATH</code> is <a href=\"https://core.trac.wordpress.org/browser/trunk/wp-config-sample.php#L84\" rel=\"nofollow noreferrer\">defined in wp-config.php</a> so works anytime after the config file is loaded, so it should be totally fine for your use.</p>\n\n<p>It is set to the <code>dirname(__FILE__) + trailing slash</code> of wp-load.php (same location as e.g. wp-config.php). <code>dirname</code> here returns the absolute path where WordPress is installed. For example, <code>/home/user/public_html</code> and <code>ABSPATH</code> adds a trailing slash</p>\n\n<pre><code>/** Absolute path to the WordPress directory. */\nif ( !defined('ABSPATH') )\n define('ABSPATH', dirname(__FILE__) . '/');\n\n// So,\nABSPATH == '/home/user/public_html/'; // WP files are in public_html\n</code></pre>\n\n<p>So if you have a folder structure such as this:</p>\n\n<pre><code>- public_html/\n- - wp-admin/\n- - wp-content/\n- - wp-includes/\n- - wp-config.php\n- - wp-load.php\n- - vendor/\n- - - autoload.php\n- ...\n</code></pre>\n\n<p>You can put the following in your theme's functions.php file to load the autoload.php file</p>\n\n<pre><code>require_once( ABSPATH . 'vendor/autoload.php' );\n</code></pre>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27866/"
] |
I was using the following: `get_home_path();` in my functions.php as referenced [in the docs](https://codex.wordpress.org/Function_Reference/get_home_path) – but I get the error:
```
Call to undefined function get_home_path() in ...
```
I'd like to include a file using it. I noticed there is also the constant `ABSPATH`. Is there any reason I shouldn't just use `ABSPATH` as an alternative to `get_home_path()`?
### Edit
I am using it as so (this is crazy simple) – in my functions.php file at the start of the file I have put:
```
require_once( ABSPATH . 'vendor/autoload.php' );
```
If I put:
```
$path = get_home_path();
require_once( $path . 'vendor/autoload.php' );
```
That's when it all goes wrong, with the generic error about the function not being available.
|
[`get_home_path()` only works when WP admin scripts are loaded.](https://codex.wordpress.org/Function_Reference/get_home_path)
`ABSPATH` is [defined in wp-config.php](https://core.trac.wordpress.org/browser/trunk/wp-config-sample.php#L84) so works anytime after the config file is loaded, so it should be totally fine for your use.
It is set to the `dirname(__FILE__) + trailing slash` of wp-load.php (same location as e.g. wp-config.php). `dirname` here returns the absolute path where WordPress is installed. For example, `/home/user/public_html` and `ABSPATH` adds a trailing slash
```
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
// So,
ABSPATH == '/home/user/public_html/'; // WP files are in public_html
```
So if you have a folder structure such as this:
```
- public_html/
- - wp-admin/
- - wp-content/
- - wp-includes/
- - wp-config.php
- - wp-load.php
- - vendor/
- - - autoload.php
- ...
```
You can put the following in your theme's functions.php file to load the autoload.php file
```
require_once( ABSPATH . 'vendor/autoload.php' );
```
|
203,489 |
<p>I want to add a media uploader to a plugin.</p>
<p>I have found and read
<a href="https://stackoverflow.com/a/28549014/3115317">This</a></p>
<p>It does shows the media uploader and it let's me select an image but as it uploads it gives me some crappy error: <code>Error occurred during upload. Try again later.</code><br>
This might be slight off because I translated it.</p>
<p>I don't know how to search for the real error here.<br>
Can anyone tell me how to find it?</p>
<pre><code><?php
wp_enqueue_script('jquery');
wp_enqueue_media();
?>
<div>
<label for="image_url">Image</label>
<input type="text" name="image_url" id="image_url" class="regular-text">
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
multiple: false
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
$('#image_url').val(image_url);
});
});
});
</script>
</code></pre>
<p>If it is possible I would like to add an items to the Media Uploader:<br>
Choose a folder to upload the file to.<br>
Not by the person who is uploading but just a folder I create before the upload</p>
<p>M.</p>
<p>---------------------------------------<br>
UPDATE:<br>
Weird thing happend<br>
I have disabled the WP_DEBUG function and now everything is working. If I set it to <code>true</code> there are no errors...</p>
|
[
{
"answer_id": 203497,
"author": "dev",
"author_id": 79859,
"author_profile": "https://wordpress.stackexchange.com/users/79859",
"pm_score": 3,
"selected": true,
"text": "<p>Try using this code:</p>\n<pre><code>define("ME_URL", rtrim(WP_PLUGIN_URL,'/') . '/' . basename(dirname(__FILE__)));\ndefine("ME_DIR", rtrim(dirname(__FILE__), '/'));\n \nfunction my_admin_scripts() {\n wp_enqueue_script('media-upload');\n wp_enqueue_script('thickbox');\n}\n \nfunction my_admin_styles() {\n wp_enqueue_style('thickbox');\n}\n \nadd_action('admin_print_scripts', 'my_admin_scripts');\nadd_action('admin_print_styles', 'my_admin_styles');\n</code></pre>\n<pre><code><td>\n <img src="<?php echo esc_attr( get_the_author_meta( 'profileimage', $user->ID ) ); ?>" id="ppimage">\n <input type="text" name="profileimage" id="profileimagetxt" value="<?php echo esc_attr( get_the_author_meta( 'profileimage', $user->ID ) ); ?>" class="regular-text" /><br />\n <input type="button" id="profileimage" value="Upload Image">\n <span class="description"><?php _e("profileimage"); ?></span>\n</td>\n</tr>\n<script type="text/javascript">\n $ = jQuery.noConflict();\n $(document).ready(function($){\n $('#profileimage').live('click',function() {\n formfield = $('#upload_image').attr('name');\n tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');\n return false;\n });\n \n window.send_to_editor = function(html) {\n imgurl = $('img',html).attr('src');\n $('#profileimagetxt').val(imgurl);\n $('#ppimage').attr('src',imgurl);\n tb_remove();\n }\n });\n</script>\n</code></pre>\n<p>Hope it works for you :)</p>\n"
},
{
"answer_id": 317254,
"author": "Rohit Kaushik",
"author_id": 125084,
"author_profile": "https://wordpress.stackexchange.com/users/125084",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this code for and here is ref. path with plugin also.\n<a href=\"http://blog.adlivetech.com/use-wordpress-media-upload-custom-code/\" rel=\"nofollow noreferrer\">http://blog.adlivetech.com/use-wordpress-media-upload-custom-code/</a></p>\n\n<pre><code><?php\nif ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :\n update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );\n endif;\n wp_enqueue_media();\n ?><form method='post'>\n <div class='image-preview-wrapper'>\n <img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' width='200'>\n </div>\n <input id=\"upload_image_button\" type=\"button\" class=\"button\" value=\"<?php _e( 'Upload image' ); ?>\" />\n <input type='hidden' name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>\n <input type=\"submit\" name=\"submit_image_selector\" value=\"Save\" class=\"button-primary\">\n </form>\n<?php\n$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );\n ?><script type='text/javascript'>\n jQuery( document ).ready( function( $ ) {\n // Uploading files\n var file_frame;\n var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id\n var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this\n jQuery('#upload_image_button').on('click', function( event ){\n event.preventDefault();\n // If the media frame already exists, reopen it.\n if ( file_frame ) {\n // Set the post ID to what we want\n file_frame.uploader.uploader.param( 'post_id', set_to_post_id );\n // Open frame\n file_frame.open();\n return;\n } else {\n // Set the wp.media post id so the uploader grabs the ID we want when initialised\n wp.media.model.settings.post.id = set_to_post_id;\n }\n // Create the media frame.\n file_frame = wp.media.frames.file_frame = wp.media({\n title: 'Select a image to upload',\n button: {\n text: 'Use this image',\n },\n multiple: false // Set to true to allow multiple files to be selected\n });\n // When an image is selected, run a callback.\n file_frame.on( 'select', function() {\n // We set multiple to false so only get one image from the uploader\n attachment = file_frame.state().get('selection').first().toJSON();\n // Do something with attachment.id and/or attachment.url here\n $( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );\n $( '#image_attachment_id' ).val( attachment.id );\n // Restore the main post ID\n wp.media.model.settings.post.id = wp_media_post_id;\n });\n // Finally, open the modal\n file_frame.open();\n });\n // Restore the main ID when the add media button is pressed\n jQuery( 'a.add_media' ).on( 'click', function() {\n wp.media.model.settings.post.id = wp_media_post_id;\n });\n });\n </script>\n</code></pre>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52240/"
] |
I want to add a media uploader to a plugin.
I have found and read
[This](https://stackoverflow.com/a/28549014/3115317)
It does shows the media uploader and it let's me select an image but as it uploads it gives me some crappy error: `Error occurred during upload. Try again later.`
This might be slight off because I translated it.
I don't know how to search for the real error here.
Can anyone tell me how to find it?
```
<?php
wp_enqueue_script('jquery');
wp_enqueue_media();
?>
<div>
<label for="image_url">Image</label>
<input type="text" name="image_url" id="image_url" class="regular-text">
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
multiple: false
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
$('#image_url').val(image_url);
});
});
});
</script>
```
If it is possible I would like to add an items to the Media Uploader:
Choose a folder to upload the file to.
Not by the person who is uploading but just a folder I create before the upload
M.
---------------------------------------
UPDATE:
Weird thing happend
I have disabled the WP\_DEBUG function and now everything is working. If I set it to `true` there are no errors...
|
Try using this code:
```
define("ME_URL", rtrim(WP_PLUGIN_URL,'/') . '/' . basename(dirname(__FILE__)));
define("ME_DIR", rtrim(dirname(__FILE__), '/'));
function my_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');
```
```
<td>
<img src="<?php echo esc_attr( get_the_author_meta( 'profileimage', $user->ID ) ); ?>" id="ppimage">
<input type="text" name="profileimage" id="profileimagetxt" value="<?php echo esc_attr( get_the_author_meta( 'profileimage', $user->ID ) ); ?>" class="regular-text" /><br />
<input type="button" id="profileimage" value="Upload Image">
<span class="description"><?php _e("profileimage"); ?></span>
</td>
</tr>
<script type="text/javascript">
$ = jQuery.noConflict();
$(document).ready(function($){
$('#profileimage').live('click',function() {
formfield = $('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = $('img',html).attr('src');
$('#profileimagetxt').val(imgurl);
$('#ppimage').attr('src',imgurl);
tb_remove();
}
});
</script>
```
Hope it works for you :)
|
203,491 |
<p>I have a Wordpress blog hosted on a server without outgoing network. Therefore, Wordpress cannot check for a new version and/or update automatically to a new version.</p>
<p>Currently, the only ways I'm aware of to update the blog to a new version of WP is to follow the complicated guide <a href="https://codex.wordpress.org/Updating_WordPress" rel="nofollow">here</a>, or to copy it to another host (with outgoing network), update it, and copy it back. Both ways are very complicated.</p>
<p>I'm looking for a way to use the automatic updater of WP without requiring outgoing network on the host. Basically, I'd like to upload <code>wordpress-4.3.1.zip</code> via FTP, go to the admin panel, and choose "update from zip file: <code>wordpress-4.3.1.zip</code>". Is there such an option, or a plugin that can help me achieve that?</p>
<p><strong>Edit:</strong> Note that I don't have access to run arbitrary code on the server. Basically, I have PHP, MySQL, FTP, and that's it.</p>
|
[
{
"answer_id": 203492,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": false,
"text": "<p>I often do Manual Update, it's not that pain. :)</p>\n\n<p>Just do it in this way (I hope you know how to update manually):</p>\n\n<p><strong>Step 1:</strong> Remove <code>wp-includes</code>, and <code>wp-admin</code> from Server and Upload new two<br>\n<strong>Step 2:</strong> Cut/Copy all the loose files from <em>local folder</em> and Paste them to the server root with Overwrite permission - <strong>Just a replace</strong><br></p>\n\n<p>And you are done. :)</p>\n\n<p><strong>Optional Step 1:</strong> In <code>wp-content/themes/</code> Delete default Theme folders and upload the latest folders, if you use them.<br>\n<strong>Optional Step 2:</strong> In <code>wp-content/plugins/</code> Delete \"Akismet\" folder, and upload latest \"Akismet\" if you use this.</p>\n\n<p><strong>P.S.:</strong> Don't delete <code>wp-content</code>, <code>.htaccess</code>, <code>wp-config.php</code>, <code>robots.txt</code> etc.</p>\n"
},
{
"answer_id": 203493,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 3,
"selected": false,
"text": "<p>As so often, <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">WP-CLI</a> already has you covered:</p>\n\n<pre><code>wp core update --version=3.8 ../latest.zip\n</code></pre>\n\n<p>Have a look here for more details:\n<a href=\"http://wp-cli.org/commands/core/update/\" rel=\"noreferrer\">http://wp-cli.org/commands/core/update/</a></p>\n"
},
{
"answer_id": 203554,
"author": "Paul",
"author_id": 80853,
"author_profile": "https://wordpress.stackexchange.com/users/80853",
"pm_score": 1,
"selected": true,
"text": "<p>Here's how it can be done, by temporarily making a minor fixup to the WP code:</p>\n\n<ol>\n<li>Upload the zip file to the root folder of WP, in the same folder as <code>wp-config.php</code> and friends.</li>\n<li>Open the file <code>wp-admin\\includes\\update.php</code>.</li>\n<li><p>Find the function <code>find_core_update</code>, and change it to:</p>\n\n<pre><code>function find_core_update( $version, $locale ) {\n $updates = get_core_updates();\n return $updates[0];\n}\n</code></pre></li>\n<li><p>Find the function <code>get_core_updates</code>, and change it to:</p>\n\n<pre><code>function get_core_updates( $options = array() ) {\n $new_zip = 'wordpress-4.3.1.zip';\n $new_version = '4.3.1';\n return array((object)array(\n 'response' => 'upgrade',\n 'current' => $new_version,\n 'download' => '../' . $new_zip,\n 'packages' => (object) array (\n 'partial' => null,\n 'new_bundled' => null,\n 'no_content' => null,\n 'full' => '../' . $new_zip,\n ),\n 'version' => $new_version,\n 'locale' => null\n ));\n}\n</code></pre>\n\n<p>Set the <code>$new_zip</code>, <code>$new_version</code> variables as needed.</p></li>\n<li><p>Go to the admin panel and run the update!</p></li>\n</ol>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203491",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80853/"
] |
I have a Wordpress blog hosted on a server without outgoing network. Therefore, Wordpress cannot check for a new version and/or update automatically to a new version.
Currently, the only ways I'm aware of to update the blog to a new version of WP is to follow the complicated guide [here](https://codex.wordpress.org/Updating_WordPress), or to copy it to another host (with outgoing network), update it, and copy it back. Both ways are very complicated.
I'm looking for a way to use the automatic updater of WP without requiring outgoing network on the host. Basically, I'd like to upload `wordpress-4.3.1.zip` via FTP, go to the admin panel, and choose "update from zip file: `wordpress-4.3.1.zip`". Is there such an option, or a plugin that can help me achieve that?
**Edit:** Note that I don't have access to run arbitrary code on the server. Basically, I have PHP, MySQL, FTP, and that's it.
|
Here's how it can be done, by temporarily making a minor fixup to the WP code:
1. Upload the zip file to the root folder of WP, in the same folder as `wp-config.php` and friends.
2. Open the file `wp-admin\includes\update.php`.
3. Find the function `find_core_update`, and change it to:
```
function find_core_update( $version, $locale ) {
$updates = get_core_updates();
return $updates[0];
}
```
4. Find the function `get_core_updates`, and change it to:
```
function get_core_updates( $options = array() ) {
$new_zip = 'wordpress-4.3.1.zip';
$new_version = '4.3.1';
return array((object)array(
'response' => 'upgrade',
'current' => $new_version,
'download' => '../' . $new_zip,
'packages' => (object) array (
'partial' => null,
'new_bundled' => null,
'no_content' => null,
'full' => '../' . $new_zip,
),
'version' => $new_version,
'locale' => null
));
}
```
Set the `$new_zip`, `$new_version` variables as needed.
5. Go to the admin panel and run the update!
|
203,495 |
<p>While achieving localization of my theme, I am getting a warning:</p>
<blockquote>
<p>Warning: fopen(C:\xampp\htdocs/wp-content/themes/themename/languages): failed to open stream: Permission denied in C:\xampp\htdocs\wp-includes\pomo\streams.php on line 145 </p>
</blockquote>
<p>When I comment line for loading text_domain in functions.php as follows:
<code>load_textdomain( 'themename', get_template_directory() . '/languages' );</code>
aforementioned warning doesn't show up.</p>
<p>I have uploaded required .po and .mo files in <code>themename/languages</code> folder.
I have also set <code>WP_LAN</code>G to <code>hi_IN</code> in <code>WP-CONFIG.php</code></p>
<p>I am using xampp installation of WordPress on localhost on my windows machine.
PHP Version 5.5.11
Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11
So how can I get rid of this warning and achieve localization?</p>
|
[
{
"answer_id": 203502,
"author": "JDP",
"author_id": 57909,
"author_profile": "https://wordpress.stackexchange.com/users/57909",
"pm_score": 0,
"selected": false,
"text": "<p>I made a huge mistake by using function <code>load_textdomain</code>. While typing the code I used the auto suggest function in Sublime-Text and got it all wrong. So use <code>load_theme_textdomain</code></p>\n"
},
{
"answer_id": 289786,
"author": "Lorenzo Magon",
"author_id": 129620,
"author_profile": "https://wordpress.stackexchange.com/users/129620",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use <strong>load_textdomain</strong> you must also specify the file name:</p>\n\n<pre><code>function my_custom_locale() \n{\n load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-\n '.get_locale().'.mo');\n}\nadd_action('after_setup_theme', 'my_custom_locale');\n</code></pre>\n\n<p>In my example I added custom translations used in additional template files placed inside the <strong>theme-child</strong> folder, where I also added the <strong>languages</strong> files folder (es. my-name-it_IT.mo, my-name-en_GB.mo).</p>\n\n<p>I added the code in the function.php file of the child-theme.</p>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203495",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57909/"
] |
While achieving localization of my theme, I am getting a warning:
>
> Warning: fopen(C:\xampp\htdocs/wp-content/themes/themename/languages): failed to open stream: Permission denied in C:\xampp\htdocs\wp-includes\pomo\streams.php on line 145
>
>
>
When I comment line for loading text\_domain in functions.php as follows:
`load_textdomain( 'themename', get_template_directory() . '/languages' );`
aforementioned warning doesn't show up.
I have uploaded required .po and .mo files in `themename/languages` folder.
I have also set `WP_LAN`G to `hi_IN` in `WP-CONFIG.php`
I am using xampp installation of WordPress on localhost on my windows machine.
PHP Version 5.5.11
Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.11
So how can I get rid of this warning and achieve localization?
|
If you want to use **load\_textdomain** you must also specify the file name:
```
function my_custom_locale()
{
load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-
'.get_locale().'.mo');
}
add_action('after_setup_theme', 'my_custom_locale');
```
In my example I added custom translations used in additional template files placed inside the **theme-child** folder, where I also added the **languages** files folder (es. my-name-it\_IT.mo, my-name-en\_GB.mo).
I added the code in the function.php file of the child-theme.
|
203,496 |
<p>I know I can edit the items within the wp_nav_menu by declaring a custom walker, but I want to add some code just inside the container, which isn't handled by a walker.</p>
<p>It's in nav-menu-menu-template.php, so I can get the desired effect by adding my code after line 329...</p>
<pre><code>$nav_menu .= "<div class='topper'>
<a href='".get_home_url()."' class='intranet'>H</a>
</div>";
</code></pre>
<p>...but of course this will disappear on an update. What hook do I need to achieve the same?</p>
|
[
{
"answer_id": 203502,
"author": "JDP",
"author_id": 57909,
"author_profile": "https://wordpress.stackexchange.com/users/57909",
"pm_score": 0,
"selected": false,
"text": "<p>I made a huge mistake by using function <code>load_textdomain</code>. While typing the code I used the auto suggest function in Sublime-Text and got it all wrong. So use <code>load_theme_textdomain</code></p>\n"
},
{
"answer_id": 289786,
"author": "Lorenzo Magon",
"author_id": 129620,
"author_profile": "https://wordpress.stackexchange.com/users/129620",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use <strong>load_textdomain</strong> you must also specify the file name:</p>\n\n<pre><code>function my_custom_locale() \n{\n load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-\n '.get_locale().'.mo');\n}\nadd_action('after_setup_theme', 'my_custom_locale');\n</code></pre>\n\n<p>In my example I added custom translations used in additional template files placed inside the <strong>theme-child</strong> folder, where I also added the <strong>languages</strong> files folder (es. my-name-it_IT.mo, my-name-en_GB.mo).</p>\n\n<p>I added the code in the function.php file of the child-theme.</p>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63673/"
] |
I know I can edit the items within the wp\_nav\_menu by declaring a custom walker, but I want to add some code just inside the container, which isn't handled by a walker.
It's in nav-menu-menu-template.php, so I can get the desired effect by adding my code after line 329...
```
$nav_menu .= "<div class='topper'>
<a href='".get_home_url()."' class='intranet'>H</a>
</div>";
```
...but of course this will disappear on an update. What hook do I need to achieve the same?
|
If you want to use **load\_textdomain** you must also specify the file name:
```
function my_custom_locale()
{
load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-
'.get_locale().'.mo');
}
add_action('after_setup_theme', 'my_custom_locale');
```
In my example I added custom translations used in additional template files placed inside the **theme-child** folder, where I also added the **languages** files folder (es. my-name-it\_IT.mo, my-name-en\_GB.mo).
I added the code in the function.php file of the child-theme.
|
203,501 |
<p>I am creating a wordpress website (colorsplash.info/vinovekitchenware/). Currently I am stuck with the following problem: i want to remove the white space between the header and the slider. After spending 2 to 3 hours, i am still unable to remove the space between these two section of div.</p>
<p>Here is the div section:</p>
<p>header id="header" class="col-full parent"> // it contains header section</p>
<p>section id="main" class="col-left"> // it contains slider section</p>
<p>Please help me!!</p>
|
[
{
"answer_id": 203502,
"author": "JDP",
"author_id": 57909,
"author_profile": "https://wordpress.stackexchange.com/users/57909",
"pm_score": 0,
"selected": false,
"text": "<p>I made a huge mistake by using function <code>load_textdomain</code>. While typing the code I used the auto suggest function in Sublime-Text and got it all wrong. So use <code>load_theme_textdomain</code></p>\n"
},
{
"answer_id": 289786,
"author": "Lorenzo Magon",
"author_id": 129620,
"author_profile": "https://wordpress.stackexchange.com/users/129620",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use <strong>load_textdomain</strong> you must also specify the file name:</p>\n\n<pre><code>function my_custom_locale() \n{\n load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-\n '.get_locale().'.mo');\n}\nadd_action('after_setup_theme', 'my_custom_locale');\n</code></pre>\n\n<p>In my example I added custom translations used in additional template files placed inside the <strong>theme-child</strong> folder, where I also added the <strong>languages</strong> files folder (es. my-name-it_IT.mo, my-name-en_GB.mo).</p>\n\n<p>I added the code in the function.php file of the child-theme.</p>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203501",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80510/"
] |
I am creating a wordpress website (colorsplash.info/vinovekitchenware/). Currently I am stuck with the following problem: i want to remove the white space between the header and the slider. After spending 2 to 3 hours, i am still unable to remove the space between these two section of div.
Here is the div section:
header id="header" class="col-full parent"> // it contains header section
section id="main" class="col-left"> // it contains slider section
Please help me!!
|
If you want to use **load\_textdomain** you must also specify the file name:
```
function my_custom_locale()
{
load_textdomain('my-name', get_stylesheet_directory().'/languages/my-name-
'.get_locale().'.mo');
}
add_action('after_setup_theme', 'my_custom_locale');
```
In my example I added custom translations used in additional template files placed inside the **theme-child** folder, where I also added the **languages** files folder (es. my-name-it\_IT.mo, my-name-en\_GB.mo).
I added the code in the function.php file of the child-theme.
|
203,529 |
<p>I have 2 custom post types "Shops" and "Restaurants".</p>
<p>Each of these have custom fields associcated with them.</p>
<p>For example, One field in Shops is "Shop ID" and one in Restaurants is "Restaurant ID".</p>
<p>I want to query both Custom Post Types and if Shop ID is 20, I want to display all Restaurants with ID 20.</p>
<p>I've been toying with this code:</p>
<pre><code> <?php
$args = array(
'numberposts' => -1,
'post_type' => 'shops', 'restaurants',
'meta_query' => array(
'relation' => 'AND',
array(
'meta_key' => 'shop-id',
'meta_value' => '12345',
'compare' => '='
),
array(
'meta_key' => 'restaurant-id',
'meta_value' => '12345',
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h4>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h4>
<?php endwhile; ?>
<?php endif; ?>
</code></pre>
<p>Note I'm also using Advanced Custom Fields.</p>
|
[
{
"answer_id": 203538,
"author": "Dunimas",
"author_id": 80863,
"author_profile": "https://wordpress.stackexchange.com/users/80863",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of a way to do this using WP_Query, but you can write custom SQL to achieve this:</p>\n\n<pre><code>global $wpdb;\n\n$id = '20';\n\n$sql = \"SELECT * FROM $wpdb->posts p\nLEFT JOIN $wpdb->postmeta pm ON p.ID = pm.post_id AND pm.meta_key IN ('shop-id','restaurant-id')\nWHERE p.post_type IN ('shops','restaurants')\nAND (\n ( pm.meta_key = 'shop-id' AND pm.meta_value = %i )\n OR ( pm.meta_key = 'restaurant-id' AND pm.meta_value = %i )\n)\";\n\n$query = $wpdb->get_results($wpdb->prepare($sql,$id));\n</code></pre>\n\n<p>This will get back all the results where the post type is a shop or restaurant, and where the shop-id or restaurant-id matches the provided ID.</p>\n"
},
{
"answer_id": 203564,
"author": "karpstrucking",
"author_id": 55214,
"author_profile": "https://wordpress.stackexchange.com/users/55214",
"pm_score": 3,
"selected": true,
"text": "<p>There's some contradiction between your question and the code you provided, so I'm not exactly sure which of two scenarios you're dealing with.</p>\n\n<p>Scenario 1 - You want to show all Shops with a specific value for <code>shop-id</code> and all Restaurants with the same specific value for <code>restaurant-id</code>. Let's say that value is 20. You can do this with a single <code>WP_Query()</code> loop that looks for both post types where either custom field has the specified value. This assumes that Shops will never have a value for <code>restaurant-id</code> and vice-versa.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => -1,\n 'post_type' => array( 'shop', 'restaurant' ),\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'restaurant-id',\n 'value' => 20,\n 'compare' => '='\n ),\n array(\n 'key' => 'shop-id',\n 'value' => 20,\n 'compare' => '='\n )\n )\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Scenario 2 - You want to show all Shops, each Shop followed by all Restaurants that have the same value for <code>restaurant-id</code> as the value of the current Shop's <code>shop-id</code>.</p>\n\n<pre><code>$shops = new WP_Query(\n array(\n 'posts_per_page' => -1,\n 'post_type' => 'shop'\n )\n);\n\nif ( $shops->have_posts() ) {\n while ( $shops->have_posts() ) {\n $shops->the_post();\n ...\n $shop_id = get_post_meta( $post->ID, 'shop-id', true );\n $restaurants = new WP_Query(\n array(\n 'posts_per_page' => -1,\n 'post_type' => 'restaurant',\n 'meta_query' => array(\n array(\n 'key' => 'restaurant-id',\n 'value' => $shop_id,\n 'compare' => '='\n )\n )\n )\n );\n if ( $restaurants->have_posts() ) {\n while ( $restaurants->have_posts() ) {\n $restaurants->the_post();\n ...\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 203581,
"author": "user636096",
"author_id": 80867,
"author_profile": "https://wordpress.stackexchange.com/users/80867",
"pm_score": 0,
"selected": false,
"text": "<p>This works below, but I only want it to compare the values and return \"shops\", at the moment, it is returning both shop and restaurants where the value is 20!</p>\n\n<pre><code> $args = array(\n 'posts_per_page' => -1,\n 'post_type' => array( 'shop', 'restaurant' ),\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'restaurant-id',\n 'value' => 20,\n 'compare' => '='\n ),\n array(\n 'key' => 'shop-id',\n 'value' => 20,\n 'compare' => '='\n )\n )\n );\n $query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203529",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80867/"
] |
I have 2 custom post types "Shops" and "Restaurants".
Each of these have custom fields associcated with them.
For example, One field in Shops is "Shop ID" and one in Restaurants is "Restaurant ID".
I want to query both Custom Post Types and if Shop ID is 20, I want to display all Restaurants with ID 20.
I've been toying with this code:
```
<?php
$args = array(
'numberposts' => -1,
'post_type' => 'shops', 'restaurants',
'meta_query' => array(
'relation' => 'AND',
array(
'meta_key' => 'shop-id',
'meta_value' => '12345',
'compare' => '='
),
array(
'meta_key' => 'restaurant-id',
'meta_value' => '12345',
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h4>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h4>
<?php endwhile; ?>
<?php endif; ?>
```
Note I'm also using Advanced Custom Fields.
|
There's some contradiction between your question and the code you provided, so I'm not exactly sure which of two scenarios you're dealing with.
Scenario 1 - You want to show all Shops with a specific value for `shop-id` and all Restaurants with the same specific value for `restaurant-id`. Let's say that value is 20. You can do this with a single `WP_Query()` loop that looks for both post types where either custom field has the specified value. This assumes that Shops will never have a value for `restaurant-id` and vice-versa.
```
$args = array(
'posts_per_page' => -1,
'post_type' => array( 'shop', 'restaurant' ),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'restaurant-id',
'value' => 20,
'compare' => '='
),
array(
'key' => 'shop-id',
'value' => 20,
'compare' => '='
)
)
);
$query = new WP_Query( $args );
```
Scenario 2 - You want to show all Shops, each Shop followed by all Restaurants that have the same value for `restaurant-id` as the value of the current Shop's `shop-id`.
```
$shops = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'shop'
)
);
if ( $shops->have_posts() ) {
while ( $shops->have_posts() ) {
$shops->the_post();
...
$shop_id = get_post_meta( $post->ID, 'shop-id', true );
$restaurants = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'restaurant',
'meta_query' => array(
array(
'key' => 'restaurant-id',
'value' => $shop_id,
'compare' => '='
)
)
)
);
if ( $restaurants->have_posts() ) {
while ( $restaurants->have_posts() ) {
$restaurants->the_post();
...
}
}
}
}
```
|
203,541 |
<p>I have a very simple JS script called <code>script_1.js</code> sitting at the root level of my twentytwelve-child theme. This script contains only:</p>
<pre><code>$(document).ready(function(){console.log("scriptLoaded");
});
</code></pre>
<p>and I've loaded it with the <code>functions.php</code>:</p>
<pre><code>function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style',
get_template_directory_uri() . '/style.css'
);
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'parent-style' )
);
}
function wpb_adding_scripts() {
wp_register_script( 'my_script',
get_stylesheet_directory_uri() . '/script_1.js',
array( 'jquery' ),
null,
true
);
wp_enqueue_script( 'my_script' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
</code></pre>
<p>Now, I read the documentation and I found that if I want to put jQuery first, I have to use the above syntax, hence <code>array( 'jquery' )</code>.</p>
<p>The problem is, that it still doesn't work and in the console I still get the usual:</p>
<pre><code>TypeError: $ is not a function
$(document).ready(function(){
</code></pre>
<p>There is a link where you can see the problem occurring, <a href="http://antonioborrillo.co.uk/andys/" rel="nofollow noreferrer">here it is</a> (error in the console).</p>
<p>Does anybody know why this isn't working? Did I incorrectly enqueue jQuery or something?
I've seen a few examples, like <a href="https://wordpress.stackexchange.com/questions/48530/how-do-i-make-script-load-after-jquery">this one</a> and that's where I took inspiration from, but no joy. </p>
|
[
{
"answer_id": 203542,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 1,
"selected": false,
"text": "<p>Try two things - <br>\n1. Link your js using <code>wp_enqueue_script</code> action as under : </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n\nfunction theme_name_scripts() {\n wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '', true);\n}\n</code></pre>\n\n<p>Third parameter in wp_enqueue_script() function will make sure jquery is loaded before your current js file.</p>\n\n<ol start=\"2\">\n<li><p>Inside your js file, replace <code>$</code> with <code>jQuery</code> as :</p>\n\n<p>jQuery(document).ready(function(){console.log(\"scriptLoaded\");\n});</p></li>\n</ol>\n"
},
{
"answer_id": 373962,
"author": "ivan rusin",
"author_id": 177043,
"author_profile": "https://wordpress.stackexchange.com/users/177043",
"pm_score": 0,
"selected": false,
"text": "<p>Also you can just wrap all your JS code by that construction:</p>\n<pre><code>(function($){\n\n // all your jQuery functions here\n\n})(jQuery);\n</code></pre>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80875/"
] |
I have a very simple JS script called `script_1.js` sitting at the root level of my twentytwelve-child theme. This script contains only:
```
$(document).ready(function(){console.log("scriptLoaded");
});
```
and I've loaded it with the `functions.php`:
```
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style',
get_template_directory_uri() . '/style.css'
);
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( 'parent-style' )
);
}
function wpb_adding_scripts() {
wp_register_script( 'my_script',
get_stylesheet_directory_uri() . '/script_1.js',
array( 'jquery' ),
null,
true
);
wp_enqueue_script( 'my_script' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
```
Now, I read the documentation and I found that if I want to put jQuery first, I have to use the above syntax, hence `array( 'jquery' )`.
The problem is, that it still doesn't work and in the console I still get the usual:
```
TypeError: $ is not a function
$(document).ready(function(){
```
There is a link where you can see the problem occurring, [here it is](http://antonioborrillo.co.uk/andys/) (error in the console).
Does anybody know why this isn't working? Did I incorrectly enqueue jQuery or something?
I've seen a few examples, like [this one](https://wordpress.stackexchange.com/questions/48530/how-do-i-make-script-load-after-jquery) and that's where I took inspiration from, but no joy.
|
Try two things -
1. Link your js using `wp_enqueue_script` action as under :
```
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
function theme_name_scripts() {
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '', true);
}
```
Third parameter in wp\_enqueue\_script() function will make sure jquery is loaded before your current js file.
2. Inside your js file, replace `$` with `jQuery` as :
jQuery(document).ready(function(){console.log("scriptLoaded");
});
|
203,556 |
<p><strong>EDIT: Rewrote the page from scratch and have been unable to figure out the differences. The new page works as expected.</strong></p>
<p>Checked multiple questions here and also on Wordpress.org with no luck yet. Below is code I'm using in several page to take old records and plug them into the DB (with no issues on those pages). There's more code further in the page but this is where I'm having issues. It's not working on one page.</p>
<p>I'm not getting any errors, even with $wpdb->show_errors(); Only output I'm getting is after I use $wpdb->print_error(), which gives me the output:</p>
<pre><code>`WordPress database error: []
SHOW FULL COLUMNS FROM `wp_posts`
</code></pre>
<p>$new_id = $wpdb->insert_id;
$new_id at this point is 0 because nothing was inserted into the DB (verified via PHPMyAdmin).</p>
<p>I've tried to indicate what types of data I'm passing in the insert (via third array of '%s', etc) but got the same results.</p>
<p>Any recommendations of other tests or workarounds would be appreciated.</p>
<p>=====================</p>
<pre><code>function transfer_officer($old_record) {
global $wpdb;
$wpdb->show_errors();
$status = 'publish';
$old_id = $old_record[0];
$name = $old_record[1];
$post_date = date('Y-m-d h:i:s');
$post_data = array(
'post_author' => 1,
'post_date' => $post_date,
'post_date_gmt' => $post_date,
'post_content' => '',
'post_title' => $name,
'post_excerpt' => '',
'post_status' => $status,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => '',
'post_name' => officer_name_to_slug($name),
'to_ping' => '',
'pinged' => '',
'post_modified' => $post_date,
'post_modified_gmt' => $post_date,
'post_content_filtered' => '',
'post_parent' => 0,
'menu_order' => 0,
'post_type' => 'rb_board_officers_posts',
'post_mime_type' => '',
'comment_count' => 0
);
//put into post table
$wpdb->insert('wp_posts', $post_data);
$wpdb->print_error();
var_dump($wpdb);
$new_id = $wpdb->insert_id;
</code></pre>
|
[
{
"answer_id": 203586,
"author": "Dave McCourt",
"author_id": 28355,
"author_profile": "https://wordpress.stackexchange.com/users/28355",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried using manually entered data to see if that gets inserted? Just make some stuff up to replace the variables. Also check that the post_author has permission to insert posts.</p>\n\n<p>Another option is to try wp_insert_post() and see if that works.</p>\n"
},
{
"answer_id": 220194,
"author": "John Joseph Adigue",
"author_id": 90266,
"author_profile": "https://wordpress.stackexchange.com/users/90266",
"pm_score": 3,
"selected": false,
"text": "<p>I got the same problem.</p>\n\n<p><strong>Solution 1:</strong>\nStrip your data.. Wordpress rejects the query if the length of value is greater than the field length defined on the database.</p>\n\n<p>On your insert query, the value for <strong>post_type</strong> field exceeded the 20 character limit.</p>\n\n<p><strong>Solution 2:</strong>\nUse the $wpdb->query method</p>\n"
},
{
"answer_id": 348626,
"author": "Rocky Mehta",
"author_id": 175384,
"author_profile": "https://wordpress.stackexchange.com/users/175384",
"pm_score": 2,
"selected": false,
"text": "<p>Hopefully, you define global variable = $wpdb.</p>\n\n<p>If your $wpdb not working, and also not showing any error then you must try these three steps.</p>\n\n<ol>\n<li><p>Print your error using with errors functions.</p>\n\n<p><code>echo $wpdb->last_error; </code></p>\n\n<p><code>or</code></p>\n\n<p><code>echo $wpdb->show_errors();</code><br><br></p></li>\n<li><p>If no error visible then you must print your last query using with last query function.</p>\n\n<p><code>echo $wpdb->last_query();</code><br><br></p></li>\n<li><p>Copy and paste your last query in your Phpmyadmin > Your Database -> Table -> SQL tab, click on Go button, you will definitely get proper solutions(errors) in it.</p></li>\n</ol>\n\n<p>Thanks,</p>\n\n<p>Rocky Mehta.</p>\n"
}
] |
2015/09/23
|
[
"https://wordpress.stackexchange.com/questions/203556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73022/"
] |
**EDIT: Rewrote the page from scratch and have been unable to figure out the differences. The new page works as expected.**
Checked multiple questions here and also on Wordpress.org with no luck yet. Below is code I'm using in several page to take old records and plug them into the DB (with no issues on those pages). There's more code further in the page but this is where I'm having issues. It's not working on one page.
I'm not getting any errors, even with $wpdb->show\_errors(); Only output I'm getting is after I use $wpdb->print\_error(), which gives me the output:
```
`WordPress database error: []
SHOW FULL COLUMNS FROM `wp_posts`
```
$new\_id = $wpdb->insert\_id;
$new\_id at this point is 0 because nothing was inserted into the DB (verified via PHPMyAdmin).
I've tried to indicate what types of data I'm passing in the insert (via third array of '%s', etc) but got the same results.
Any recommendations of other tests or workarounds would be appreciated.
=====================
```
function transfer_officer($old_record) {
global $wpdb;
$wpdb->show_errors();
$status = 'publish';
$old_id = $old_record[0];
$name = $old_record[1];
$post_date = date('Y-m-d h:i:s');
$post_data = array(
'post_author' => 1,
'post_date' => $post_date,
'post_date_gmt' => $post_date,
'post_content' => '',
'post_title' => $name,
'post_excerpt' => '',
'post_status' => $status,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => '',
'post_name' => officer_name_to_slug($name),
'to_ping' => '',
'pinged' => '',
'post_modified' => $post_date,
'post_modified_gmt' => $post_date,
'post_content_filtered' => '',
'post_parent' => 0,
'menu_order' => 0,
'post_type' => 'rb_board_officers_posts',
'post_mime_type' => '',
'comment_count' => 0
);
//put into post table
$wpdb->insert('wp_posts', $post_data);
$wpdb->print_error();
var_dump($wpdb);
$new_id = $wpdb->insert_id;
```
|
I got the same problem.
**Solution 1:**
Strip your data.. Wordpress rejects the query if the length of value is greater than the field length defined on the database.
On your insert query, the value for **post\_type** field exceeded the 20 character limit.
**Solution 2:**
Use the $wpdb->query method
|
203,571 |
<p>I use the below code . But the code display Thumbnail in the five number column. How to move it first column position? </p>
<pre><code>//show Thumbnail in dashboard
function my_function_admin_bar(){ return false; }
add_filter( 'show_admin_bar' , 'my_function_admin_bar');
add_image_size( 'admin-list-thumb', 80, 80, false );
add_filter('manage_posts_columns', 'tcb_add_post_thumbnail_column', 1);
add_filter('manage_pages_columns', 'tcb_add_post_thumbnail_column', 1);
function tcb_add_post_thumbnail_column($cols){
$cols['tcb_post_thumb'] = __('Thumbnail');
return $cols;
}
add_action('manage_posts_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);
add_action('manage_pages_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);
function tcb_display_post_thumbnail_column($col, $id){
switch($col){
case 'tcb_post_thumb':
if( function_exists('the_post_thumbnail') )
echo the_post_thumbnail( 'admin-list-thumb' );
else
echo 'Not supported in theme';
break;
}
}
</code></pre>
|
[
{
"answer_id": 203573,
"author": "Nick",
"author_id": 65003,
"author_profile": "https://wordpress.stackexchange.com/users/65003",
"pm_score": 3,
"selected": true,
"text": "<p>You can add featured image thumbnail in post column with this code.</p>\n\n<p>Copied from here <a href=\"http://wpcodesnippet.com/add-featured-post-thumbnails-to-post-columns/\" rel=\"nofollow\">Add Featured Post Thumbnails to WordPress Admin Post Columns</a>.\nHaven't tried it myself but it must work.</p>\n\n<pre><code>add_image_size( 'admin-list-thumb', 80, 80, false );\n\n// add featured thumbnail to admin post columns\nfunction wpcs_add_thumbnail_columns( $columns ) {\n $columns = array(\n 'cb' => '<input type=\"checkbox\" />',\n 'featured_thumb' => 'Thumbnail',\n 'title' => 'Title',\n 'author' => 'Author',\n 'categories' => 'Categories',\n 'tags' => 'Tags',\n 'comments' => '<span class=\"vers\"><div title=\"Comments\" class=\"comment-grey-bubble\"></div></span>',\n 'date' => 'Date'\n );\n return $columns;\n}\n\nfunction wpcs_add_thumbnail_columns_data( $column, $post_id ) {\n switch ( $column ) {\n case 'featured_thumb':\n echo '<a href=\"' . get_edit_post_link() . '\">';\n echo the_post_thumbnail( 'admin-list-thumb' );\n echo '</a>';\n break;\n }\n}\n\nif ( function_exists( 'add_theme_support' ) ) {\n add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' );\n add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );\n add_filter( 'manage_pages_columns' , 'wpcs_add_thumbnail_columns' );\n add_action( 'manage_pages_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just tried it and it's working fine.</p>\n\n<p>Although it works fine out of the box but you can change thumbnail size in above code if you want to use your custom defined image size.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just fixed this code for 80x80 thumbnail.</p>\n"
},
{
"answer_id": 364862,
"author": "Husky",
"author_id": 649,
"author_profile": "https://wordpress.stackexchange.com/users/649",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a slightly cleaner version of the code posted by <a href=\"https://wordpress.stackexchange.com/users/65003/nick\">Nick</a>. A couple of differences:</p>\n\n<ul>\n<li>I'm using anonymous functions to avoid cluttering the global namespace. Note that if you only need to add the code to a single post type, you can also use a closure:</li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('manage_posts_columns', function() {\n // Do your thing here\n});\n</code></pre>\n\n<ul>\n<li>Instead of returning a completely new <code>$columns</code> array, i'm adding the column in the existing array. If another column is added (either by a WordPress update or another piece of code), this method won't break that.</li>\n<li>A simple <code>if</code> in the <code>manage_posts_custom_column</code> hook instead of a <code>switch</code> seems to make more sense here. </li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_image_size(\"admin-list-thumb\", 80, 80, false);\n\n$cols_fn = function($cols) {\n $col_position = 1; // Change this to another position if you want\n\n return array_merge(\n array_splice($cols, 0, $col_position),\n [\"admin-thumb\" => \"Thumb\"],\n $cols\n );\n};\n\n$custom_cols_fn = function($col, $id) {\n if ($col == \"admin-thumb\") {\n $link = get_edit_post_link();\n $thumb = get_the_post_thumbnail($id, \"admin-list-thumb\");\n echo $thumb ? \"<a href='$link'>$thumb</a>\" : \"—\";\n }\n};\n\nadd_filter('manage_posts_columns', $cols_fn);\nadd_action('manage_posts_custom_column', $custom_cols_fn, 10, 2 );\nadd_filter('manage_pages_columns', $cols_fn);\nadd_action('manage_pages_custom_column', $custom_cols_fn, 10, 2 );\n</code></pre>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68406/"
] |
I use the below code . But the code display Thumbnail in the five number column. How to move it first column position?
```
//show Thumbnail in dashboard
function my_function_admin_bar(){ return false; }
add_filter( 'show_admin_bar' , 'my_function_admin_bar');
add_image_size( 'admin-list-thumb', 80, 80, false );
add_filter('manage_posts_columns', 'tcb_add_post_thumbnail_column', 1);
add_filter('manage_pages_columns', 'tcb_add_post_thumbnail_column', 1);
function tcb_add_post_thumbnail_column($cols){
$cols['tcb_post_thumb'] = __('Thumbnail');
return $cols;
}
add_action('manage_posts_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);
add_action('manage_pages_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);
function tcb_display_post_thumbnail_column($col, $id){
switch($col){
case 'tcb_post_thumb':
if( function_exists('the_post_thumbnail') )
echo the_post_thumbnail( 'admin-list-thumb' );
else
echo 'Not supported in theme';
break;
}
}
```
|
You can add featured image thumbnail in post column with this code.
Copied from here [Add Featured Post Thumbnails to WordPress Admin Post Columns](http://wpcodesnippet.com/add-featured-post-thumbnails-to-post-columns/).
Haven't tried it myself but it must work.
```
add_image_size( 'admin-list-thumb', 80, 80, false );
// add featured thumbnail to admin post columns
function wpcs_add_thumbnail_columns( $columns ) {
$columns = array(
'cb' => '<input type="checkbox" />',
'featured_thumb' => 'Thumbnail',
'title' => 'Title',
'author' => 'Author',
'categories' => 'Categories',
'tags' => 'Tags',
'comments' => '<span class="vers"><div title="Comments" class="comment-grey-bubble"></div></span>',
'date' => 'Date'
);
return $columns;
}
function wpcs_add_thumbnail_columns_data( $column, $post_id ) {
switch ( $column ) {
case 'featured_thumb':
echo '<a href="' . get_edit_post_link() . '">';
echo the_post_thumbnail( 'admin-list-thumb' );
echo '</a>';
break;
}
}
if ( function_exists( 'add_theme_support' ) ) {
add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' );
add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );
add_filter( 'manage_pages_columns' , 'wpcs_add_thumbnail_columns' );
add_action( 'manage_pages_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );
}
```
**EDIT**
Just tried it and it's working fine.
Although it works fine out of the box but you can change thumbnail size in above code if you want to use your custom defined image size.
**EDIT**
Just fixed this code for 80x80 thumbnail.
|
203,587 |
<p>Total wordpress beginner here. I purchased a organicfood theme and when I got an updated version for it, among other files I also found organicfood child theme zip in main directory.</p>
<p>I know that organicfood.zip contains the updated version of parent theme but I don't know if same goes for organicfood child theme zip. Is the child zip added with every update just so that a new buyer has that default child theme template?</p>
|
[
{
"answer_id": 203573,
"author": "Nick",
"author_id": 65003,
"author_profile": "https://wordpress.stackexchange.com/users/65003",
"pm_score": 3,
"selected": true,
"text": "<p>You can add featured image thumbnail in post column with this code.</p>\n\n<p>Copied from here <a href=\"http://wpcodesnippet.com/add-featured-post-thumbnails-to-post-columns/\" rel=\"nofollow\">Add Featured Post Thumbnails to WordPress Admin Post Columns</a>.\nHaven't tried it myself but it must work.</p>\n\n<pre><code>add_image_size( 'admin-list-thumb', 80, 80, false );\n\n// add featured thumbnail to admin post columns\nfunction wpcs_add_thumbnail_columns( $columns ) {\n $columns = array(\n 'cb' => '<input type=\"checkbox\" />',\n 'featured_thumb' => 'Thumbnail',\n 'title' => 'Title',\n 'author' => 'Author',\n 'categories' => 'Categories',\n 'tags' => 'Tags',\n 'comments' => '<span class=\"vers\"><div title=\"Comments\" class=\"comment-grey-bubble\"></div></span>',\n 'date' => 'Date'\n );\n return $columns;\n}\n\nfunction wpcs_add_thumbnail_columns_data( $column, $post_id ) {\n switch ( $column ) {\n case 'featured_thumb':\n echo '<a href=\"' . get_edit_post_link() . '\">';\n echo the_post_thumbnail( 'admin-list-thumb' );\n echo '</a>';\n break;\n }\n}\n\nif ( function_exists( 'add_theme_support' ) ) {\n add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' );\n add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );\n add_filter( 'manage_pages_columns' , 'wpcs_add_thumbnail_columns' );\n add_action( 'manage_pages_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );\n}\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just tried it and it's working fine.</p>\n\n<p>Although it works fine out of the box but you can change thumbnail size in above code if you want to use your custom defined image size.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just fixed this code for 80x80 thumbnail.</p>\n"
},
{
"answer_id": 364862,
"author": "Husky",
"author_id": 649,
"author_profile": "https://wordpress.stackexchange.com/users/649",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a slightly cleaner version of the code posted by <a href=\"https://wordpress.stackexchange.com/users/65003/nick\">Nick</a>. A couple of differences:</p>\n\n<ul>\n<li>I'm using anonymous functions to avoid cluttering the global namespace. Note that if you only need to add the code to a single post type, you can also use a closure:</li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('manage_posts_columns', function() {\n // Do your thing here\n});\n</code></pre>\n\n<ul>\n<li>Instead of returning a completely new <code>$columns</code> array, i'm adding the column in the existing array. If another column is added (either by a WordPress update or another piece of code), this method won't break that.</li>\n<li>A simple <code>if</code> in the <code>manage_posts_custom_column</code> hook instead of a <code>switch</code> seems to make more sense here. </li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_image_size(\"admin-list-thumb\", 80, 80, false);\n\n$cols_fn = function($cols) {\n $col_position = 1; // Change this to another position if you want\n\n return array_merge(\n array_splice($cols, 0, $col_position),\n [\"admin-thumb\" => \"Thumb\"],\n $cols\n );\n};\n\n$custom_cols_fn = function($col, $id) {\n if ($col == \"admin-thumb\") {\n $link = get_edit_post_link();\n $thumb = get_the_post_thumbnail($id, \"admin-list-thumb\");\n echo $thumb ? \"<a href='$link'>$thumb</a>\" : \"—\";\n }\n};\n\nadd_filter('manage_posts_columns', $cols_fn);\nadd_action('manage_posts_custom_column', $custom_cols_fn, 10, 2 );\nadd_filter('manage_pages_columns', $cols_fn);\nadd_action('manage_pages_custom_column', $custom_cols_fn, 10, 2 );\n</code></pre>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80902/"
] |
Total wordpress beginner here. I purchased a organicfood theme and when I got an updated version for it, among other files I also found organicfood child theme zip in main directory.
I know that organicfood.zip contains the updated version of parent theme but I don't know if same goes for organicfood child theme zip. Is the child zip added with every update just so that a new buyer has that default child theme template?
|
You can add featured image thumbnail in post column with this code.
Copied from here [Add Featured Post Thumbnails to WordPress Admin Post Columns](http://wpcodesnippet.com/add-featured-post-thumbnails-to-post-columns/).
Haven't tried it myself but it must work.
```
add_image_size( 'admin-list-thumb', 80, 80, false );
// add featured thumbnail to admin post columns
function wpcs_add_thumbnail_columns( $columns ) {
$columns = array(
'cb' => '<input type="checkbox" />',
'featured_thumb' => 'Thumbnail',
'title' => 'Title',
'author' => 'Author',
'categories' => 'Categories',
'tags' => 'Tags',
'comments' => '<span class="vers"><div title="Comments" class="comment-grey-bubble"></div></span>',
'date' => 'Date'
);
return $columns;
}
function wpcs_add_thumbnail_columns_data( $column, $post_id ) {
switch ( $column ) {
case 'featured_thumb':
echo '<a href="' . get_edit_post_link() . '">';
echo the_post_thumbnail( 'admin-list-thumb' );
echo '</a>';
break;
}
}
if ( function_exists( 'add_theme_support' ) ) {
add_filter( 'manage_posts_columns' , 'wpcs_add_thumbnail_columns' );
add_action( 'manage_posts_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );
add_filter( 'manage_pages_columns' , 'wpcs_add_thumbnail_columns' );
add_action( 'manage_pages_custom_column' , 'wpcs_add_thumbnail_columns_data', 10, 2 );
}
```
**EDIT**
Just tried it and it's working fine.
Although it works fine out of the box but you can change thumbnail size in above code if you want to use your custom defined image size.
**EDIT**
Just fixed this code for 80x80 thumbnail.
|
203,599 |
<p>Plugin in question: <a href="http://dimsemenov.com/plugins/royal-slider/wordpress/" rel="nofollow">http://dimsemenov.com/plugins/royal-slider/wordpress/</a></p>
<p>Background: This is a great plugin, and it features a 'post' version where the slider pulls content from posts. However, the taxonomy for the posts that it's pulling has to be set at the slider settings level in WordPress, it can't be done via shortcode (that we know of). The plugin author does offer a way to override the default query here: <a href="http://help.dimsemenov.com/kb/wordpress-royalslider-advanced/wp-modifying-order-of-posts-in-slider" rel="nofollow">http://help.dimsemenov.com/kb/wordpress-royalslider-advanced/wp-modifying-order-of-posts-in-slider</a></p>
<p>Aim: create a custom shortcode through which we can pass custom attributes, and specifically taxonomy, post-type.</p>
<blockquote>
<blockquote>
<p>Example of what the shortcode would look like: [rscustom rsid="2" rstax="home" rspt="carousel-slide"]</p>
</blockquote>
</blockquote>
<p>Our issue: probably a dumb one, but I can't get the shortcode variables to 'pass into' the query function, my code:</p>
<pre><code>function rscustom_shortcode( $atts, $content = null ) {
// Extract variables from shortcode attributes: post type, id, taxonomy
$a = shortcode_atts( array(
'rspt' => '',
'rsid' => '',
'rstax' => '',
), $atts );
$rspt = trim($a['rspt']);
$rsid = trim($a['rsid']);
$rstax = trim($a['rstax']);
// Execute the Royal Slider Query Override
add_filter('new_royalslider_posts_slider_query_args', 'newrs_custom_query', 10, $rsid);
function newrs_custom_query($args) {
$args = array(
'post_type' => 'carousel-slide',
'orderby' => array(
'menu_order' => 'ASC'
),
'tax_query' => array(
array(
'taxonomy' => 'carousel-slide-category',
'field' => 'slug',
'terms' => "$rstax", // THIS VARIABLE ISN'T PASSING INTO THE FUNCTION
),
),
);
return $args;
};
return get_new_royalslider($rsid);
}
add_shortcode( 'rscustom', 'rscustom_shortcode' );
</code></pre>
<p>The line where I have...</p>
<blockquote>
<blockquote>
<p>'terms' => "$rstax"</p>
</blockquote>
</blockquote>
<p>...seems to be the bit where I'm hung up. When I have the line as... </p>
<blockquote>
<blockquote>
<p>'terms' => 'home' </p>
</blockquote>
</blockquote>
<p>...everything works wonderfully. I've looked into global variables, but just managed to confuse myself more.</p>
<p>Any and all help would be very, very much appreciated. Thanks in advance!</p>
|
[
{
"answer_id": 203597,
"author": "Aravona",
"author_id": 49852,
"author_profile": "https://wordpress.stackexchange.com/users/49852",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?</p>\n</blockquote>\n\n<p>This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)</p>\n\n<blockquote>\n <p>How likely is it that someone unwanted infiltrates the WordPress admin area?</p>\n</blockquote>\n\n<p>This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc. </p>\n\n<p>The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.</p>\n\n<p>WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.</p>\n"
},
{
"answer_id": 203613,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so an admin gets full-on hacked. You're screwed. No matter what. <strong>But</strong> what if it's a localised/specific XSS attack? What if the file editor is disabled on the system? What if the request is genuine but the admin has accidentally pasted a bunch of crap that's gonna bork your beautiful theme?</p>\n\n<p>These are all scenarios you can protect against. Ultimately the argument will always be you have <strong>nothing to lose</strong> and everything to gain from correctly sanitizing and escaping.</p>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47880/"
] |
Plugin in question: <http://dimsemenov.com/plugins/royal-slider/wordpress/>
Background: This is a great plugin, and it features a 'post' version where the slider pulls content from posts. However, the taxonomy for the posts that it's pulling has to be set at the slider settings level in WordPress, it can't be done via shortcode (that we know of). The plugin author does offer a way to override the default query here: <http://help.dimsemenov.com/kb/wordpress-royalslider-advanced/wp-modifying-order-of-posts-in-slider>
Aim: create a custom shortcode through which we can pass custom attributes, and specifically taxonomy, post-type.
>
>
> >
> > Example of what the shortcode would look like: [rscustom rsid="2" rstax="home" rspt="carousel-slide"]
> >
> >
> >
>
>
>
Our issue: probably a dumb one, but I can't get the shortcode variables to 'pass into' the query function, my code:
```
function rscustom_shortcode( $atts, $content = null ) {
// Extract variables from shortcode attributes: post type, id, taxonomy
$a = shortcode_atts( array(
'rspt' => '',
'rsid' => '',
'rstax' => '',
), $atts );
$rspt = trim($a['rspt']);
$rsid = trim($a['rsid']);
$rstax = trim($a['rstax']);
// Execute the Royal Slider Query Override
add_filter('new_royalslider_posts_slider_query_args', 'newrs_custom_query', 10, $rsid);
function newrs_custom_query($args) {
$args = array(
'post_type' => 'carousel-slide',
'orderby' => array(
'menu_order' => 'ASC'
),
'tax_query' => array(
array(
'taxonomy' => 'carousel-slide-category',
'field' => 'slug',
'terms' => "$rstax", // THIS VARIABLE ISN'T PASSING INTO THE FUNCTION
),
),
);
return $args;
};
return get_new_royalslider($rsid);
}
add_shortcode( 'rscustom', 'rscustom_shortcode' );
```
The line where I have...
>
>
> >
> > 'terms' => "$rstax"
> >
> >
> >
>
>
>
...seems to be the bit where I'm hung up. When I have the line as...
>
>
> >
> > 'terms' => 'home'
> >
> >
> >
>
>
>
...everything works wonderfully. I've looked into global variables, but just managed to confuse myself more.
Any and all help would be very, very much appreciated. Thanks in advance!
|
>
> If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?
>
>
>
This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)
>
> How likely is it that someone unwanted infiltrates the WordPress admin area?
>
>
>
This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc.
The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.
WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.
|
203,618 |
<p>I need to add new sidebars for using them accordingly on different pages throughout my shop.</p>
<p>I use Woocommerce and my own Storefront child theme.</p>
<p>This is a snippet of what is in functions.php file of the child theme.</p>
<pre><code>add_action( 'init', 'init_storefront_child' );
function init_storefront_child() {
// It seems Wordpress doesn't take into consideration the 2 lines below.
remove_action( 'widgets_init', 'storefront_widgets_init' ); // Not fired (or overrided by something)
add_action( 'widgets_init', 'storefront_child_widgets_init' ); // Not fired (or overrided by something)
}
function storefront_child_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar' ),
'id' => 'blog',
'description' => 'Sidebar displaying in blog.',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
</code></pre>
<p>So the sidebars in 'Appearance > Widgets' menu don't change and stay the same as originally.</p>
<p>I tried to change the code directly in storefront theme files and it works but that's not at all the solution.</p>
<p>What's happen with the 'widgets_init' hook in functions.php's child theme?</p>
<p>Thanks by advance.</p>
|
[
{
"answer_id": 203597,
"author": "Aravona",
"author_id": 49852,
"author_profile": "https://wordpress.stackexchange.com/users/49852",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?</p>\n</blockquote>\n\n<p>This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)</p>\n\n<blockquote>\n <p>How likely is it that someone unwanted infiltrates the WordPress admin area?</p>\n</blockquote>\n\n<p>This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc. </p>\n\n<p>The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.</p>\n\n<p>WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.</p>\n"
},
{
"answer_id": 203613,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so an admin gets full-on hacked. You're screwed. No matter what. <strong>But</strong> what if it's a localised/specific XSS attack? What if the file editor is disabled on the system? What if the request is genuine but the admin has accidentally pasted a bunch of crap that's gonna bork your beautiful theme?</p>\n\n<p>These are all scenarios you can protect against. Ultimately the argument will always be you have <strong>nothing to lose</strong> and everything to gain from correctly sanitizing and escaping.</p>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73239/"
] |
I need to add new sidebars for using them accordingly on different pages throughout my shop.
I use Woocommerce and my own Storefront child theme.
This is a snippet of what is in functions.php file of the child theme.
```
add_action( 'init', 'init_storefront_child' );
function init_storefront_child() {
// It seems Wordpress doesn't take into consideration the 2 lines below.
remove_action( 'widgets_init', 'storefront_widgets_init' ); // Not fired (or overrided by something)
add_action( 'widgets_init', 'storefront_child_widgets_init' ); // Not fired (or overrided by something)
}
function storefront_child_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar' ),
'id' => 'blog',
'description' => 'Sidebar displaying in blog.',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
```
So the sidebars in 'Appearance > Widgets' menu don't change and stay the same as originally.
I tried to change the code directly in storefront theme files and it works but that's not at all the solution.
What's happen with the 'widgets\_init' hook in functions.php's child theme?
Thanks by advance.
|
>
> If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?
>
>
>
This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)
>
> How likely is it that someone unwanted infiltrates the WordPress admin area?
>
>
>
This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc.
The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.
WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.
|
203,623 |
<p>Wordpress nav menu created by wp_nav_menu can highlight current menu item. How can i strip anchor from current menu item?</p>
<p>For example, we have menu:</p>
<pre><code><ul>
<li class="current-menu-item"><a href="/somelink">Home</a></li>
<li><a href="/elselink">Item</a></li>
...
</ul>
</code></pre>
<p>Can we remove</p>
<pre><code><a href="/somelink">
</code></pre>
<p>and leave just "Home" if it is current page?</p>
<p>UPD.
In my functions.php I have a walker like this:</p>
<pre><code>class My_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
}
}
</code></pre>
<p>and I've found the walker I need:</p>
<pre><code>//Creating new walker class, which won't make current page linked.
class not_linked_cur_page_MenuWalker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{ //All code below until '$current_url'
// is native Walker_Nav_Menu code. Then we compare requested URL and current URL.
// If whey are equal - the text shows in <span> tag instead of <a>.
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
$class_names = ' class="' . esc_attr( $class_names ) . '"';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$current_url = (is_ssl()?'https://':'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$item_url = esc_attr( $item->url );
if ($item_url == $current_url)
{
$item_output = $args->before;
$item_output .= '<span'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</span>';
$item_output .= $args->after;
}
else
{
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
}
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
</code></pre>
<p>How I can make one walker of these two?</p>
|
[
{
"answer_id": 203597,
"author": "Aravona",
"author_id": 49852,
"author_profile": "https://wordpress.stackexchange.com/users/49852",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?</p>\n</blockquote>\n\n<p>This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)</p>\n\n<blockquote>\n <p>How likely is it that someone unwanted infiltrates the WordPress admin area?</p>\n</blockquote>\n\n<p>This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc. </p>\n\n<p>The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.</p>\n\n<p>WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.</p>\n"
},
{
"answer_id": 203613,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, so an admin gets full-on hacked. You're screwed. No matter what. <strong>But</strong> what if it's a localised/specific XSS attack? What if the file editor is disabled on the system? What if the request is genuine but the admin has accidentally pasted a bunch of crap that's gonna bork your beautiful theme?</p>\n\n<p>These are all scenarios you can protect against. Ultimately the argument will always be you have <strong>nothing to lose</strong> and everything to gain from correctly sanitizing and escaping.</p>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203623",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80919/"
] |
Wordpress nav menu created by wp\_nav\_menu can highlight current menu item. How can i strip anchor from current menu item?
For example, we have menu:
```
<ul>
<li class="current-menu-item"><a href="/somelink">Home</a></li>
<li><a href="/elselink">Item</a></li>
...
</ul>
```
Can we remove
```
<a href="/somelink">
```
and leave just "Home" if it is current page?
UPD.
In my functions.php I have a walker like this:
```
class My_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
}
}
```
and I've found the walker I need:
```
//Creating new walker class, which won't make current page linked.
class not_linked_cur_page_MenuWalker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{ //All code below until '$current_url'
// is native Walker_Nav_Menu code. Then we compare requested URL and current URL.
// If whey are equal - the text shows in <span> tag instead of <a>.
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
$class_names = ' class="' . esc_attr( $class_names ) . '"';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$current_url = (is_ssl()?'https://':'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$item_url = esc_attr( $item->url );
if ($item_url == $current_url)
{
$item_output = $args->before;
$item_output .= '<span'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</span>';
$item_output .= $args->after;
}
else
{
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
}
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
```
How I can make one walker of these two?
|
>
> If someone has managed to access the admin area by making it look like they are someone else, isn't it all over anyway?
>
>
>
This to me is more part of your exclusions as this is the main way anyone gains access through WordPress... So not really, if you have a backup, just drop the Database, upload your backup and change the passwords - then perhaps look into additional security. A good plan is to not name the admin as admin for example (doing this on one site prevented a lot of spam attempted logins for me with people attempting to guess the password)
>
> How likely is it that someone unwanted infiltrates the WordPress admin area?
>
>
>
This depends on your set up really, what security plugins you have, or if you've manually set up any restricted access such as IP blocking for certain files. The more you put in the more they've got to deal with. Most of these are risk reduction techniques which help to prevent brute force, etc.
The only other thing I can think of is to keep your web server maintained, secure and up to date so that users cannot use vulnerability loopholes to gain access to your servers.
WordPress accept security reports so as a community the more that is brought to their attention, in theory, the more secure WordPress will become. To be honest, unless your website is popular, and getting regular spam, hits, etc, you're probably not going to be worth a hackers time.
|
203,628 |
<p>I have a widget I want only allowed to be used with the single.php sidebar. When I referenced the codex for <a href="https://codex.wordpress.org/Function_Reference/register_sidebar" rel="nofollow noreferrer"><code>register sidebar</code></a> there isn't a way to limit widgets in the array. I've researched with "WordPress limit widget to post" but they are only plugins returned in my search results. When I change my search parameters to page to see if I can get something returned I am reference to:</p>
<ul>
<li><p><a href="https://wordpress.stackexchange.com/questions/1421/disable-specific-widgets-on-selected-pages-of-a-wordpress-website">Disable Specific Widgets on Selected Pages of a WordPress Website?</a> which is five years old and suggests plugins</p></li>
<li><p><a href="https://wordpress.stackexchange.com/questions/76959/how-to-add-a-specific-widget-to-only-1-page">How to add a specific widget to only 1 page?</a> is a two year old post that mentions <code>loop_start</code> but I do not see any documentation that covers <code>loop_start</code> or how to implement it with posts.</p></li>
</ul>
<p>Is there a way that I can target a Widget to only be allowed for the <code>id</code> in the <code>register_sidebar</code>? I do not want to use a plugin I want to learn how to properly code it.</p>
<p>EDIT:</p>
<p>Per comments I have a custom widget. that is being called in my singles.php as <code><?php get_sidebar( 'foobar' );?></code>. When someone is in admin I want to limit where the widget can be applied to:</p>
<p><a href="https://i.stack.imgur.com/AK7Vy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AK7Vy.png" alt="enter image description here"></a></p>
<p>So in the image above I want there to only be the option of <code>Post Sidebar</code>. I could hard code all of this in in the <code>sidebar-foobar.php</code> file but I am trying to learn how to utilize widgets more.</p>
|
[
{
"answer_id": 204107,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>My jquery knowledge is still almost non existent, so I'm not sure if <a href=\"https://www.quora.com/WordPress-Theme-Development/Is-there-a-way-to-trigger-a-JavaScript-function-when-a-particular-widget-is-drag-and-dropped-in-widgets-php-of-the-admin-area\" rel=\"nofollow noreferrer\">the solution</a> works that was suggested by @Howdy_McGee in comments. </p>\n\n<p>Anyways, just as matter of proper reference, from the link</p>\n\n<blockquote>\n <p>just replace <code>'your_widget'</code> with name of your widget in the code below\n (two places). </p>\n \n <p><code>'sortreceive'</code> event is only called when widget is added to sidebar,\n while <code>'sortstop'</code> gets called whenever you move the widget around\n inside sidebar or remove it. </p>\n \n <p><code>'sortstop'</code> is also called when widget is added, but for some reason\n ui.input is not set properly, so i used 'sortreceive' to cover that.</p>\n\n<pre><code>jQuery('div.widgets-sortables').bind('sortstop',function(event,ui){\n var id = jQuery(ui.item).attr('id');\n if (id) {\n var widget_type = id.match(/widget-[0-9]+_(.+)-[0-9]+/i)[1];\n if (widget_type == 'your_widget') {\n // do stuff;\n }\n }\n})\n\njQuery('div.widgets-sortables').bind('sortreceive',function(event,ui){\n var id = jQuery(ui.item).attr('id');\n var widget_type = id.match(/widget-[0-9]+_(.+)-__i__/i)[1];\n if (widget_type == 'your_widget') {\n // do stuff;\n }\n})\n</code></pre>\n</blockquote>\n\n<p>I have recently worked on <a href=\"https://wordpress.stackexchange.com/a/202584/31545\">an answer</a> where a specific widget can be removed from the array of widgets from a specific sidebar. Here we use the <code>sidebars_widgets</code> filter to remove a specific widget from all sidebars except the sidebar where it should be. </p>\n\n<p>So in short, a widget that is incorrectly added to a sidebar will not show up in front end, and it will also not return true with an <code>is_active_sidebar()</code> check if that widget is the only widget added to that specific sidebar.</p>\n\n<p>You can try the following code, just be sure to change the widget and sidebar values accordingly.</p>\n\n<pre><code>add_filter( 'sidebars_widgets', function ( $sidebars_widgets )\n{\n // Return our filter when we are on admin screen\n if ( is_admin() )\n return $sidebars_widgets;\n\n /**\n * Widget we need to target. This should be the name/id we used to register it\n *\n * EXAMPLE\n * parent::__construct(\n 'widget_category_posts', \n _x( 'Category Posts Widget', 'Category Posts Widget' ), \n [ 'description' => __( 'Display a list of posts from a selected category.' ) ] \n );\n *\n */\n $custom_widget = 'widget_category_posts';\n // The sidebar ID we need to run the widget in\n $sidebar_accept = 'sidebar-2';\n\n // We have come this far, let us wrap this up\n // See if our custom content widget exists is any sidebar, if so, get the array index\n foreach ( $sidebars_widgets as $sidebars_key=>$sidebars_widget ) {\n // Skip the wp_inactive_widgets set, we do not need them\n if ( $sidebars_key == 'wp_inactive_widgets' )\n continue;\n\n // Only continue our operation if $sidebars_widget are not an empty array\n if ( $sidebars_widget ) {\n foreach ( $sidebars_widget as $k=>$v ) {\n\n /**\n * Look for our custom widget, if found, unset it from the $sidebars_widgets array\n * @see stripos()\n */\n if ( stripos( $v, $custom_widget ) !== false ) {\n // If we are on a single page and the sidebar is $sidebar_accept, do not unset\n if ( is_single() && $sidebars_key == $sidebar_accept )\n continue;\n\n unset( $sidebars_widgets[$sidebars_key][$k] );\n }\n } // endforeach $sidebars_widget\n } // endif $sidebars_widget\n } // endforeach $sidebars_widgets\n\n return $sidebars_widgets;\n});\n</code></pre>\n\n<p>In conclusion, this is just a PHP workaround which does work only for the front end, but I would urge you to still look for a proper jquery solution where a widget is only bound to a specific sidebar in the backend. As I said, the jquery solution from the link is untested and I do not know if if really works</p>\n"
},
{
"answer_id": 227234,
"author": "icetique",
"author_id": 94395,
"author_profile": "https://wordpress.stackexchange.com/users/94395",
"pm_score": 1,
"selected": false,
"text": "<p>As an addition to your scripts I wrote the script which hides sidebars from the dropdown list (I couldn't find this anywhere). I made some reverse engineering of the original widgets.js Wordpress code to write this.</p>\n\n<p>The complete solution for allowing to drag & drop only to specified sidebars and to filter the dropdown list (you just need to put this in your document ready jQuery admin script):\n</p>\n\n<pre><code>function allowedSidebars(allowed)\n{\n // this variable will have index of first visible sidebar\n var first = null;\n $('.widgets-chooser-sidebars li').removeClass('widgets-chooser-selected').each(function(index)\n {\n // the data('sidebarId') is set up by wordpress, let's make us of it\n if(-1 === $.inArray($(this).data('sidebarId'), allowed))\n {\n $(this).hide();\n }\n else if(first == null)\n {\n first = index;\n }\n });\n // choose first visible sidebar as default\n if(first != null)\n {\n $('.widgets-chooser-sidebars li').eq(first).addClass('widgets-chooser-selected');\n }\n}\n$('#available-widgets .widget .widget-title').on('click.widgets-chooser', function()\n{\n var widget = $(this).closest('.widget');\n // we want to run our script only on slideDown, not slideUp\n if(!widget.hasClass('widget-in-question'))\n {\n // there is only one sidebar list per all widgets, so we have to show all the sidebars every time\n $('.widgets-chooser-sidebars li').show();\n switch(widget.find('input[name=\"id_base\"]').val())\n {\n // your widgets here\n case 'your_widget_id':\n // allowed sidebars for widget\n allowedSidebars(['your-sidebar-id', 'your-second-sidebar-id']);\n break;\n }\n }\n});\n// this will make drag and drop working only for specified sidebars\n$('.widget').on('dragcreate dragstart', function( event, ui ) {\n var id = $(this).find('input[name=\"id_base\"]').val();\n // probably you may want to change it to switch\n if(id == 'your_widget_id')\n {\n $(this).draggable({\n connectToSortable: '#your-sidebar-id, #your-second-sidebar-id'\n });\n }\n});\n</code></pre>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] |
I have a widget I want only allowed to be used with the single.php sidebar. When I referenced the codex for [`register sidebar`](https://codex.wordpress.org/Function_Reference/register_sidebar) there isn't a way to limit widgets in the array. I've researched with "WordPress limit widget to post" but they are only plugins returned in my search results. When I change my search parameters to page to see if I can get something returned I am reference to:
* [Disable Specific Widgets on Selected Pages of a WordPress Website?](https://wordpress.stackexchange.com/questions/1421/disable-specific-widgets-on-selected-pages-of-a-wordpress-website) which is five years old and suggests plugins
* [How to add a specific widget to only 1 page?](https://wordpress.stackexchange.com/questions/76959/how-to-add-a-specific-widget-to-only-1-page) is a two year old post that mentions `loop_start` but I do not see any documentation that covers `loop_start` or how to implement it with posts.
Is there a way that I can target a Widget to only be allowed for the `id` in the `register_sidebar`? I do not want to use a plugin I want to learn how to properly code it.
EDIT:
Per comments I have a custom widget. that is being called in my singles.php as `<?php get_sidebar( 'foobar' );?>`. When someone is in admin I want to limit where the widget can be applied to:
[](https://i.stack.imgur.com/AK7Vy.png)
So in the image above I want there to only be the option of `Post Sidebar`. I could hard code all of this in in the `sidebar-foobar.php` file but I am trying to learn how to utilize widgets more.
|
My jquery knowledge is still almost non existent, so I'm not sure if [the solution](https://www.quora.com/WordPress-Theme-Development/Is-there-a-way-to-trigger-a-JavaScript-function-when-a-particular-widget-is-drag-and-dropped-in-widgets-php-of-the-admin-area) works that was suggested by @Howdy\_McGee in comments.
Anyways, just as matter of proper reference, from the link
>
> just replace `'your_widget'` with name of your widget in the code below
> (two places).
>
>
> `'sortreceive'` event is only called when widget is added to sidebar,
> while `'sortstop'` gets called whenever you move the widget around
> inside sidebar or remove it.
>
>
> `'sortstop'` is also called when widget is added, but for some reason
> ui.input is not set properly, so i used 'sortreceive' to cover that.
>
>
>
> ```
> jQuery('div.widgets-sortables').bind('sortstop',function(event,ui){
> var id = jQuery(ui.item).attr('id');
> if (id) {
> var widget_type = id.match(/widget-[0-9]+_(.+)-[0-9]+/i)[1];
> if (widget_type == 'your_widget') {
> // do stuff;
> }
> }
> })
>
> jQuery('div.widgets-sortables').bind('sortreceive',function(event,ui){
> var id = jQuery(ui.item).attr('id');
> var widget_type = id.match(/widget-[0-9]+_(.+)-__i__/i)[1];
> if (widget_type == 'your_widget') {
> // do stuff;
> }
> })
>
> ```
>
>
I have recently worked on [an answer](https://wordpress.stackexchange.com/a/202584/31545) where a specific widget can be removed from the array of widgets from a specific sidebar. Here we use the `sidebars_widgets` filter to remove a specific widget from all sidebars except the sidebar where it should be.
So in short, a widget that is incorrectly added to a sidebar will not show up in front end, and it will also not return true with an `is_active_sidebar()` check if that widget is the only widget added to that specific sidebar.
You can try the following code, just be sure to change the widget and sidebar values accordingly.
```
add_filter( 'sidebars_widgets', function ( $sidebars_widgets )
{
// Return our filter when we are on admin screen
if ( is_admin() )
return $sidebars_widgets;
/**
* Widget we need to target. This should be the name/id we used to register it
*
* EXAMPLE
* parent::__construct(
'widget_category_posts',
_x( 'Category Posts Widget', 'Category Posts Widget' ),
[ 'description' => __( 'Display a list of posts from a selected category.' ) ]
);
*
*/
$custom_widget = 'widget_category_posts';
// The sidebar ID we need to run the widget in
$sidebar_accept = 'sidebar-2';
// We have come this far, let us wrap this up
// See if our custom content widget exists is any sidebar, if so, get the array index
foreach ( $sidebars_widgets as $sidebars_key=>$sidebars_widget ) {
// Skip the wp_inactive_widgets set, we do not need them
if ( $sidebars_key == 'wp_inactive_widgets' )
continue;
// Only continue our operation if $sidebars_widget are not an empty array
if ( $sidebars_widget ) {
foreach ( $sidebars_widget as $k=>$v ) {
/**
* Look for our custom widget, if found, unset it from the $sidebars_widgets array
* @see stripos()
*/
if ( stripos( $v, $custom_widget ) !== false ) {
// If we are on a single page and the sidebar is $sidebar_accept, do not unset
if ( is_single() && $sidebars_key == $sidebar_accept )
continue;
unset( $sidebars_widgets[$sidebars_key][$k] );
}
} // endforeach $sidebars_widget
} // endif $sidebars_widget
} // endforeach $sidebars_widgets
return $sidebars_widgets;
});
```
In conclusion, this is just a PHP workaround which does work only for the front end, but I would urge you to still look for a proper jquery solution where a widget is only bound to a specific sidebar in the backend. As I said, the jquery solution from the link is untested and I do not know if if really works
|
203,639 |
<p>How do I get total number of Authors on the site?</p>
<p>This shows summery of users on the site but I just want to get number of Authors.</p>
<pre><code><?php
$result = count_users();
echo 'There are ', $result['total_users'], ' total users';
foreach($result['avail_roles'] as $role => $count)
echo ', ', $count, ' are ', $role, 's';
echo '.';
?>
</code></pre>
<p><a href="https://codex.wordpress.org/Function_Reference/count_users" rel="nofollow">https://codex.wordpress.org/Function_Reference/count_users</a></p>
|
[
{
"answer_id": 203643,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\"><code>WP_User_Query</code></a> class, like the example below. Each code line have an small description, that you understand, what we do.</p>\n\n<pre><code>// Get all users with role Author.\n$user_query = new WP_User_Query( array( 'role' => 'Author' ) );\n// Get the total number of users for the current query. I use (int) only for sanitize.\n$users_count = (int) $user_query->get_total();\n// Echo a string and the value\necho 'So much authors: ' . $users_count;\n</code></pre>\n\n<p>Alternative you can also use the function <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\"><code>get_users()</code></a>. But is only a wrapper for the query and have much more fields in the result.</p>\n"
},
{
"answer_id": 203649,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want one field and/or a count, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\">get_users()</a>. Restricting the fields returned makes for a fast query. </p>\n\n<pre><code>$users_count = count( get_users( array( 'fields' => array( 'ID' ), 'role' => 'author' ) ) );\n</code></pre>\n"
},
{
"answer_id": 278231,
"author": "Quazi Hanif Shakil",
"author_id": 126656,
"author_profile": "https://wordpress.stackexchange.com/users/126656",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want authors count</p>\n\n<pre><code> <?php\n$result = count_users();\necho count( get_users( array( 'role' => 'author' ) ) );\n?>\n</code></pre>\n"
},
{
"answer_id": 414204,
"author": "timmah.faase",
"author_id": 179273,
"author_profile": "https://wordpress.stackexchange.com/users/179273",
"pm_score": 0,
"selected": false,
"text": "<p>The WP class <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> is inefficient if all you want is a count. The constructor runs <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/query/\" rel=\"nofollow noreferrer\"><code>query()</code></a> producing an unnecessary call to <code>users</code> table, then a subsequent call with <code>SELECT FOUND_ROWS()</code>.</p>\n<p>After reviewing the wp core code we implement this filter.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('users_pre_query', function($result, WP_User_Query $user_query) {\n\n global $wpdb;\n $user_count = $wpdb->get_var("SELECT COUNT(1) {$user_query->query_from} {$user_query->query_where}");\n if(empty($wpdb->last_error)) $user_query->total_users = (int)$user_count;\n\n return false;\n}, 10, 2);\n</code></pre>\n<p>The filter prevents local <code>results</code> from running and correctly sets <code>total_users</code> for use of:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$user_query = new WP_User_Query();\n$user_query->get_total();\n</code></pre>\n<p>You'll want to remove the filter after instantiating.</p>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74171/"
] |
How do I get total number of Authors on the site?
This shows summery of users on the site but I just want to get number of Authors.
```
<?php
$result = count_users();
echo 'There are ', $result['total_users'], ' total users';
foreach($result['avail_roles'] as $role => $count)
echo ', ', $count, ' are ', $role, 's';
echo '.';
?>
```
<https://codex.wordpress.org/Function_Reference/count_users>
|
You can use the [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) class, like the example below. Each code line have an small description, that you understand, what we do.
```
// Get all users with role Author.
$user_query = new WP_User_Query( array( 'role' => 'Author' ) );
// Get the total number of users for the current query. I use (int) only for sanitize.
$users_count = (int) $user_query->get_total();
// Echo a string and the value
echo 'So much authors: ' . $users_count;
```
Alternative you can also use the function [`get_users()`](https://codex.wordpress.org/Function_Reference/get_users). But is only a wrapper for the query and have much more fields in the result.
|
203,656 |
<p>Sorry for this question, but I can't work out why my site name isn't showing in the browser window even though I have <code>wp_title()</code> in the <code><head></code>. </p>
<p>All I have done is used CSS to indent the text -9999px so it's off the screen but I thought that would still register as the title in the browser?</p>
<p>When I navigate through to posts, the post name appears, but the site name doesn't appear on those pages either, even though it should appear before the post.</p>
<p>I'm stumped. Any help would be greatly appreciated!</p>
<p>Thanks in advance!</p>
<hr>
<p>Following on from Will's advice I included the following code in the <code>functions.php</code>:</p>
<pre><code>function twentytwelve_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() )
return $title;
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
// Add a page number if necessary.
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 );
</code></pre>
<p>and then changed the <code><title></code> tag to the following: </p>
<p><code><title><?php wp_title('|', true, 'right'); ?></title></code></p>
<p>All seems to be working now! Thanks for your help!</p>
|
[
{
"answer_id": 203643,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\"><code>WP_User_Query</code></a> class, like the example below. Each code line have an small description, that you understand, what we do.</p>\n\n<pre><code>// Get all users with role Author.\n$user_query = new WP_User_Query( array( 'role' => 'Author' ) );\n// Get the total number of users for the current query. I use (int) only for sanitize.\n$users_count = (int) $user_query->get_total();\n// Echo a string and the value\necho 'So much authors: ' . $users_count;\n</code></pre>\n\n<p>Alternative you can also use the function <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\"><code>get_users()</code></a>. But is only a wrapper for the query and have much more fields in the result.</p>\n"
},
{
"answer_id": 203649,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want one field and/or a count, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\">get_users()</a>. Restricting the fields returned makes for a fast query. </p>\n\n<pre><code>$users_count = count( get_users( array( 'fields' => array( 'ID' ), 'role' => 'author' ) ) );\n</code></pre>\n"
},
{
"answer_id": 278231,
"author": "Quazi Hanif Shakil",
"author_id": 126656,
"author_profile": "https://wordpress.stackexchange.com/users/126656",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want authors count</p>\n\n<pre><code> <?php\n$result = count_users();\necho count( get_users( array( 'role' => 'author' ) ) );\n?>\n</code></pre>\n"
},
{
"answer_id": 414204,
"author": "timmah.faase",
"author_id": 179273,
"author_profile": "https://wordpress.stackexchange.com/users/179273",
"pm_score": 0,
"selected": false,
"text": "<p>The WP class <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> is inefficient if all you want is a count. The constructor runs <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/query/\" rel=\"nofollow noreferrer\"><code>query()</code></a> producing an unnecessary call to <code>users</code> table, then a subsequent call with <code>SELECT FOUND_ROWS()</code>.</p>\n<p>After reviewing the wp core code we implement this filter.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('users_pre_query', function($result, WP_User_Query $user_query) {\n\n global $wpdb;\n $user_count = $wpdb->get_var("SELECT COUNT(1) {$user_query->query_from} {$user_query->query_where}");\n if(empty($wpdb->last_error)) $user_query->total_users = (int)$user_count;\n\n return false;\n}, 10, 2);\n</code></pre>\n<p>The filter prevents local <code>results</code> from running and correctly sets <code>total_users</code> for use of:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$user_query = new WP_User_Query();\n$user_query->get_total();\n</code></pre>\n<p>You'll want to remove the filter after instantiating.</p>\n"
}
] |
2015/09/24
|
[
"https://wordpress.stackexchange.com/questions/203656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66157/"
] |
Sorry for this question, but I can't work out why my site name isn't showing in the browser window even though I have `wp_title()` in the `<head>`.
All I have done is used CSS to indent the text -9999px so it's off the screen but I thought that would still register as the title in the browser?
When I navigate through to posts, the post name appears, but the site name doesn't appear on those pages either, even though it should appear before the post.
I'm stumped. Any help would be greatly appreciated!
Thanks in advance!
---
Following on from Will's advice I included the following code in the `functions.php`:
```
function twentytwelve_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() )
return $title;
// Add the site name.
$title .= get_bloginfo( 'name' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
$title = "$title $sep $site_description";
// Add a page number if necessary.
if ( $paged >= 2 || $page >= 2 )
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 );
```
and then changed the `<title>` tag to the following:
`<title><?php wp_title('|', true, 'right'); ?></title>`
All seems to be working now! Thanks for your help!
|
You can use the [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) class, like the example below. Each code line have an small description, that you understand, what we do.
```
// Get all users with role Author.
$user_query = new WP_User_Query( array( 'role' => 'Author' ) );
// Get the total number of users for the current query. I use (int) only for sanitize.
$users_count = (int) $user_query->get_total();
// Echo a string and the value
echo 'So much authors: ' . $users_count;
```
Alternative you can also use the function [`get_users()`](https://codex.wordpress.org/Function_Reference/get_users). But is only a wrapper for the query and have much more fields in the result.
|
203,670 |
<p>I am working on <a href="http://www.kensingtonmn.com/wordpress/churches-and-schools/" rel="nofollow">this WP website</a> and can't for the life of me get the entire height of the sidebar to take the background setting.</p>
<p>The theme is a child of TwentyFourteen. Through FireFox's Inspect Element I can see my background-color setting on the #secondary div, which is the main container for the side nav area, but I can't figure out why it's not coloring the entire height of the page, nor how to get it so.</p>
|
[
{
"answer_id": 203643,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\"><code>WP_User_Query</code></a> class, like the example below. Each code line have an small description, that you understand, what we do.</p>\n\n<pre><code>// Get all users with role Author.\n$user_query = new WP_User_Query( array( 'role' => 'Author' ) );\n// Get the total number of users for the current query. I use (int) only for sanitize.\n$users_count = (int) $user_query->get_total();\n// Echo a string and the value\necho 'So much authors: ' . $users_count;\n</code></pre>\n\n<p>Alternative you can also use the function <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\"><code>get_users()</code></a>. But is only a wrapper for the query and have much more fields in the result.</p>\n"
},
{
"answer_id": 203649,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want one field and/or a count, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\">get_users()</a>. Restricting the fields returned makes for a fast query. </p>\n\n<pre><code>$users_count = count( get_users( array( 'fields' => array( 'ID' ), 'role' => 'author' ) ) );\n</code></pre>\n"
},
{
"answer_id": 278231,
"author": "Quazi Hanif Shakil",
"author_id": 126656,
"author_profile": "https://wordpress.stackexchange.com/users/126656",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want authors count</p>\n\n<pre><code> <?php\n$result = count_users();\necho count( get_users( array( 'role' => 'author' ) ) );\n?>\n</code></pre>\n"
},
{
"answer_id": 414204,
"author": "timmah.faase",
"author_id": 179273,
"author_profile": "https://wordpress.stackexchange.com/users/179273",
"pm_score": 0,
"selected": false,
"text": "<p>The WP class <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> is inefficient if all you want is a count. The constructor runs <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/query/\" rel=\"nofollow noreferrer\"><code>query()</code></a> producing an unnecessary call to <code>users</code> table, then a subsequent call with <code>SELECT FOUND_ROWS()</code>.</p>\n<p>After reviewing the wp core code we implement this filter.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('users_pre_query', function($result, WP_User_Query $user_query) {\n\n global $wpdb;\n $user_count = $wpdb->get_var("SELECT COUNT(1) {$user_query->query_from} {$user_query->query_where}");\n if(empty($wpdb->last_error)) $user_query->total_users = (int)$user_count;\n\n return false;\n}, 10, 2);\n</code></pre>\n<p>The filter prevents local <code>results</code> from running and correctly sets <code>total_users</code> for use of:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$user_query = new WP_User_Query();\n$user_query->get_total();\n</code></pre>\n<p>You'll want to remove the filter after instantiating.</p>\n"
}
] |
2015/09/25
|
[
"https://wordpress.stackexchange.com/questions/203670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73969/"
] |
I am working on [this WP website](http://www.kensingtonmn.com/wordpress/churches-and-schools/) and can't for the life of me get the entire height of the sidebar to take the background setting.
The theme is a child of TwentyFourteen. Through FireFox's Inspect Element I can see my background-color setting on the #secondary div, which is the main container for the side nav area, but I can't figure out why it's not coloring the entire height of the page, nor how to get it so.
|
You can use the [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) class, like the example below. Each code line have an small description, that you understand, what we do.
```
// Get all users with role Author.
$user_query = new WP_User_Query( array( 'role' => 'Author' ) );
// Get the total number of users for the current query. I use (int) only for sanitize.
$users_count = (int) $user_query->get_total();
// Echo a string and the value
echo 'So much authors: ' . $users_count;
```
Alternative you can also use the function [`get_users()`](https://codex.wordpress.org/Function_Reference/get_users). But is only a wrapper for the query and have much more fields in the result.
|
203,678 |
<p>I'm building a theme that generates on the home template a link to the PDF attached to the post (it will be only PDF files).</p>
<p>I found a solution to check if the post has a PDF attached. The goal is to create a link that downloads the file, on the home (blog) template.</p>
<p>Here's what I currently have</p>
<pre><code>function leoni_get_attachment() {
global $post;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'application/pdf',
'post_parent' => $post->ID,
);
$attachments = get_posts($args);
$attachment_link = wp_get_attachment_url();
if ($attachments) {
echo '<a href="'. $attachment_link .'">Download</a>';
} else {
return false;
}
}
</code></pre>
<p>I've tried using <code>get_attached_file()</code> without success.</p>
|
[
{
"answer_id": 203683,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": false,
"text": "<p>Well, there is a WP function for that.</p>\n\n<p>wp_get_attachment_url</p>\n\n<p>It takes attachment id as argument, so you can use it like in following example:</p>\n\n<pre><code>echo wp_get_attachment_url( 12 );\n</code></pre>\n\n<p>This will echo url to attachment which id is 12.</p>\n\n<p>You can find more info and examples on Codex page:\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_get_attachment_url</a></p>\n"
},
{
"answer_id": 253077,
"author": "rafsuntaskin",
"author_id": 49748,
"author_profile": "https://wordpress.stackexchange.com/users/49748",
"pm_score": 1,
"selected": false,
"text": "<pre><code> $attachment_link = wp_get_attachment_url( $attachments[0]->ID );\n</code></pre>\n\n<p>Try replacing your link with, this one. You need to pass an argument to get the url which is the attachment ID.</p>\n"
}
] |
2015/09/25
|
[
"https://wordpress.stackexchange.com/questions/203678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43151/"
] |
I'm building a theme that generates on the home template a link to the PDF attached to the post (it will be only PDF files).
I found a solution to check if the post has a PDF attached. The goal is to create a link that downloads the file, on the home (blog) template.
Here's what I currently have
```
function leoni_get_attachment() {
global $post;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'application/pdf',
'post_parent' => $post->ID,
);
$attachments = get_posts($args);
$attachment_link = wp_get_attachment_url();
if ($attachments) {
echo '<a href="'. $attachment_link .'">Download</a>';
} else {
return false;
}
}
```
I've tried using `get_attached_file()` without success.
|
Well, there is a WP function for that.
wp\_get\_attachment\_url
It takes attachment id as argument, so you can use it like in following example:
```
echo wp_get_attachment_url( 12 );
```
This will echo url to attachment which id is 12.
You can find more info and examples on Codex page:
<https://codex.wordpress.org/Function_Reference/wp_get_attachment_url>
|
203,715 |
<p>I'm a bit confused with templates for custom post types defined as hierarchical. I've got a CPT set to hierarchical, not strictly in order to have a nested hierarchy, but so that they can be ordered by the Simple Page Ordering plugin. Here's the code:</p>
<pre><code>register_post_type(
'case_study', array(
'label' => _x( 'case studies', 'post type plural name' ),
'labels' => array(
'name' => _x( 'Case studies', 'post type general name' ),
'singular_name' => _x( 'Case study', 'post type singular name' ),
'menu_name' => _x( 'Case studies', 'admin menu' ),
'name_admin_bar' => _x( 'Case study', 'add new on admin bar' ),
'add_new' => _x( 'Add New', 'case study' ),
'add_new_item' => __( 'Add New Case study' ),
'new_item' => __( 'New Case study' ),
'edit_item' => __( 'Edit Case study' ),
'view_item' => __( 'View Case study' ),
'all_items' => __( 'All Case studies' ),
'search_items' => __( 'Search Case studies' ),
'parent_item_colon' => __( 'Parent Case studies:' ),
'not_found' => __( 'No Case studies found.' ),
'not_found_in_trash' => __( 'No Case studies found in Trash.' )
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 20, // Below Pages
'menu_icon' => 'dashicons-clipboard', // @link https://developer.wordpress.org/resource/dashicons/
'query_var' => false,
'rewrite' => array( 'slug' => 'case-study', 'with_front' => false ),
'capability_type' => 'case_study',
'map_meta_cap' => false,
'capabilities' => array(
'publish_posts' => 'publish_case_studies',
'edit_posts' => 'edit_case_studies',
'edit_others_posts' => 'edit_others_case_studies',
'delete_posts' => 'delete_case_studies',
'delete_others_posts' => 'delete_others_case_studies',
'read_private_posts' => 'read_private_case_studies',
'edit_post' => 'edit_case_study',
'delete_post' => 'delete_case_study',
'read_post' => 'read_case_study',
),
'has_archive' => false,
'hierarchical' => true, // Set to true to allow ordering
'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'revisions', 'pilau-author' ),
'taxonomies' => array( 'topic' ),
)
);
</code></pre>
<p>By default a hierarchical CPT uses the page.php template instead of single.php - which took me a while to realise, but it makes sense.</p>
<p>However, now I want to create a template specifically for this CPT, and single-case_study.php doesn't work. Neither does page-case_study.php.</p>
<p>How do you create a template specifically for a hierarchical CPT?</p>
|
[
{
"answer_id": 203852,
"author": "Steve Taylor",
"author_id": 2336,
"author_profile": "https://wordpress.stackexchange.com/users/2336",
"pm_score": 0,
"selected": false,
"text": "<p>I sense I'm still missing something, but for now I've approached this another way. Since the only reason for the CPT to have <code>hierarchical</code> set to <code>true</code> is so that <a href=\"https://wordpress.org/plugins/simple-page-ordering/\" rel=\"nofollow\">Simple Page Ordering</a> will work (I'm not actually after a nested hierarchy), I went back to the plugin's FAQ and found that it is possible to order non-hierarchical post types. Either include <code>'page-attributes'</code> in the <code>supports</code> array or use the <code>simple_page_ordering_is_sortable</code> filter, then you can click 'Sort by Order' on the posts admin listing page and drag-and-drop.</p>\n"
},
{
"answer_id": 403350,
"author": "amapparat",
"author_id": 208935,
"author_profile": "https://wordpress.stackexchange.com/users/208935",
"pm_score": 1,
"selected": false,
"text": "<p>Old question but maybe it helps someone else:</p>\n<p>You could do something like this in page.php:</p>\n<pre><code>$postType = get_post_type();\n\nif($postType == 'case_study'){\n include('single-case_study.php');\n} else{\n // Do your page.php stuff\n</code></pre>\n"
}
] |
2015/09/25
|
[
"https://wordpress.stackexchange.com/questions/203715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2336/"
] |
I'm a bit confused with templates for custom post types defined as hierarchical. I've got a CPT set to hierarchical, not strictly in order to have a nested hierarchy, but so that they can be ordered by the Simple Page Ordering plugin. Here's the code:
```
register_post_type(
'case_study', array(
'label' => _x( 'case studies', 'post type plural name' ),
'labels' => array(
'name' => _x( 'Case studies', 'post type general name' ),
'singular_name' => _x( 'Case study', 'post type singular name' ),
'menu_name' => _x( 'Case studies', 'admin menu' ),
'name_admin_bar' => _x( 'Case study', 'add new on admin bar' ),
'add_new' => _x( 'Add New', 'case study' ),
'add_new_item' => __( 'Add New Case study' ),
'new_item' => __( 'New Case study' ),
'edit_item' => __( 'Edit Case study' ),
'view_item' => __( 'View Case study' ),
'all_items' => __( 'All Case studies' ),
'search_items' => __( 'Search Case studies' ),
'parent_item_colon' => __( 'Parent Case studies:' ),
'not_found' => __( 'No Case studies found.' ),
'not_found_in_trash' => __( 'No Case studies found in Trash.' )
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 20, // Below Pages
'menu_icon' => 'dashicons-clipboard', // @link https://developer.wordpress.org/resource/dashicons/
'query_var' => false,
'rewrite' => array( 'slug' => 'case-study', 'with_front' => false ),
'capability_type' => 'case_study',
'map_meta_cap' => false,
'capabilities' => array(
'publish_posts' => 'publish_case_studies',
'edit_posts' => 'edit_case_studies',
'edit_others_posts' => 'edit_others_case_studies',
'delete_posts' => 'delete_case_studies',
'delete_others_posts' => 'delete_others_case_studies',
'read_private_posts' => 'read_private_case_studies',
'edit_post' => 'edit_case_study',
'delete_post' => 'delete_case_study',
'read_post' => 'read_case_study',
),
'has_archive' => false,
'hierarchical' => true, // Set to true to allow ordering
'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'revisions', 'pilau-author' ),
'taxonomies' => array( 'topic' ),
)
);
```
By default a hierarchical CPT uses the page.php template instead of single.php - which took me a while to realise, but it makes sense.
However, now I want to create a template specifically for this CPT, and single-case\_study.php doesn't work. Neither does page-case\_study.php.
How do you create a template specifically for a hierarchical CPT?
|
Old question but maybe it helps someone else:
You could do something like this in page.php:
```
$postType = get_post_type();
if($postType == 'case_study'){
include('single-case_study.php');
} else{
// Do your page.php stuff
```
|
203,717 |
<p><a href="https://i.stack.imgur.com/XT3hX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XT3hX.jpg" alt="enter image description here"></a></p>
<p>Hi. I don't know ajax programming. I know HTML, CSS, little bit of php(so much that I am editing and customizing all the default themes, and learning along the way). </p>
<p>I have attached the UI of the page which my designer has designed. Now I am making this in wordpress. I have assigned the left menu as the category menu, so it has categories of all the posts.</p>
<p>I can create different templates for trending posts and fresh posts. So basically I will have then 3 templates for the category page (default, trending and fresh)</p>
<p>What I would like to know is how to display a separate menu for trending, fresh and default. Eg if the user is on default page (home page), then the category menu on the left will use the default template, when he is on the trending page, the category menu on the left will use the trending template and so on. Is there a simple way to do this ? Can I do this with ajax too ? </p>
<p>The theme is twenty fourteen child ..</p>
|
[
{
"answer_id": 203852,
"author": "Steve Taylor",
"author_id": 2336,
"author_profile": "https://wordpress.stackexchange.com/users/2336",
"pm_score": 0,
"selected": false,
"text": "<p>I sense I'm still missing something, but for now I've approached this another way. Since the only reason for the CPT to have <code>hierarchical</code> set to <code>true</code> is so that <a href=\"https://wordpress.org/plugins/simple-page-ordering/\" rel=\"nofollow\">Simple Page Ordering</a> will work (I'm not actually after a nested hierarchy), I went back to the plugin's FAQ and found that it is possible to order non-hierarchical post types. Either include <code>'page-attributes'</code> in the <code>supports</code> array or use the <code>simple_page_ordering_is_sortable</code> filter, then you can click 'Sort by Order' on the posts admin listing page and drag-and-drop.</p>\n"
},
{
"answer_id": 403350,
"author": "amapparat",
"author_id": 208935,
"author_profile": "https://wordpress.stackexchange.com/users/208935",
"pm_score": 1,
"selected": false,
"text": "<p>Old question but maybe it helps someone else:</p>\n<p>You could do something like this in page.php:</p>\n<pre><code>$postType = get_post_type();\n\nif($postType == 'case_study'){\n include('single-case_study.php');\n} else{\n // Do your page.php stuff\n</code></pre>\n"
}
] |
2015/09/25
|
[
"https://wordpress.stackexchange.com/questions/203717",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80956/"
] |
[](https://i.stack.imgur.com/XT3hX.jpg)
Hi. I don't know ajax programming. I know HTML, CSS, little bit of php(so much that I am editing and customizing all the default themes, and learning along the way).
I have attached the UI of the page which my designer has designed. Now I am making this in wordpress. I have assigned the left menu as the category menu, so it has categories of all the posts.
I can create different templates for trending posts and fresh posts. So basically I will have then 3 templates for the category page (default, trending and fresh)
What I would like to know is how to display a separate menu for trending, fresh and default. Eg if the user is on default page (home page), then the category menu on the left will use the default template, when he is on the trending page, the category menu on the left will use the trending template and so on. Is there a simple way to do this ? Can I do this with ajax too ?
The theme is twenty fourteen child ..
|
Old question but maybe it helps someone else:
You could do something like this in page.php:
```
$postType = get_post_type();
if($postType == 'case_study'){
include('single-case_study.php');
} else{
// Do your page.php stuff
```
|
203,750 |
<p>guys! I'm pretty sure this will be a piece of cake for y`all, but I'm trying to add pagination to my loop. I've tried some codes that were available around, and got to paginate it, but pages 2, 3, etc had the same content from page 1. What's the best solution for what I have at the moment?</p>
<pre><code><?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<article>
</article>
<?php endwhile; ?>
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 203759,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>There are few ways to do <a href=\"https://codex.wordpress.org/Pagination\" rel=\"nofollow\">pagination</a>. Here is one:</p>\n\n<pre><code><?php $query = new WP_Query( array( 'posts_per_page' => 5 ) ); ?>\n\n<?php while ($query->have_posts()) : $query->the_post(); ?>\n <article>\n <h2><a href=\"<?php the_permalink(); ?>\" rel=\"bookmark\" title=\"Permanent Link to <?php the_title_attribute(); ?>\"><?php the_title(); ?></a></h2>\n <article>\n<?php endwhile; ?>\n\n<div class=\"nav-previous alignleft\"><?php next_posts_link( 'Older posts' ); ?></div>\n<div class=\"nav-next alignright\"><?php previous_posts_link( 'Newer posts' ); ?></div>\n</code></pre>\n\n<p>Of course it won't work if your WP_Query is not built correctly.</p>\n"
},
{
"answer_id": 203770,
"author": "amespower",
"author_id": 24339,
"author_profile": "https://wordpress.stackexchange.com/users/24339",
"pm_score": 3,
"selected": false,
"text": "<p>Likely this is happening because you are using a custom page template. Try the following. I've commented the steps along the way. Hope it helps.</p>\n\n<pre><code><?php \n //get the current page\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n\n //pagination fixes prior to loop\n $temp = $query;\n $query = null;\n\n //custom loop using WP_Query\n $query = new WP_Query( array( \n 'post_status' => 'publish',\n 'orderby' => 'date',\n 'order' => 'ASC' \n ) ); \n\n //set our query's pagination to $paged\n $query -> query('post_type=post&posts_per_page=5'.'&paged='.$paged);\n\n if ( $query->have_posts() ) : \n while ( $query->have_posts() ) : $query->the_post();\n ?>\n <li>\n <?php if ( has_post_thumbnail()) : ?>\n <?php the_post_thumbnail();?>\n <?php endif; ?>\n <div class=\"someclass\" >\n <h2><?php the_title(); ?></h2> \n <?php the_content(); ?>\n </div> \n </li>\n <?php endwhile;?>\n\n <?php //pass in the max_num_pages, which is total pages ?>\n <div class=\"pagenav\">\n <div class=\"alignleft\"><?php previous_posts_link('Previous', $query->max_num_pages) ?></div>\n <div class=\"alignright\"><?php next_posts_link('Next', $query->max_num_pages) ?></div>\n </div>\n\n<?php endif; ?>\n\n<?php //reset the following that was set above prior to loop\n$query = null; $query = $temp; ?>\n</code></pre>\n"
},
{
"answer_id": 203782,
"author": "Sindhu",
"author_id": 80578,
"author_profile": "https://wordpress.stackexchange.com/users/80578",
"pm_score": 0,
"selected": false,
"text": "<p>Here my post type is 'news_events', the pagination will be displayed after every 4 posts title is displayed. </p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$news_events = array( 'post_type' => 'news_events', 'posts_per_page' => 4, 'paged' => $paged);\n$wp_query = new WP_Query( $news_events );\nif ( $wp_query->have_posts() ) : ?>\n <?php while ( $wp_query->have_posts() ) : $wp_query->the_post();?>\n <?php the_title(); echo \"<br/>\"; ?>\n <?php endwhile; ?>\n <nav>\n <?php previous_posts_link('&laquo; Newer',$wp_query->max_num_pages); ?>\n <?php next_posts_link('Older &raquo;',$wp_query->max_num_pages); ?>\n </nav>\n <?php wp_reset_postdata(); ?> \n <?php else : ?>\n <p><?php _e( 'Sorry, no news events posts at this time.', 'theme' ); ?></p>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2015/09/25
|
[
"https://wordpress.stackexchange.com/questions/203750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78848/"
] |
guys! I'm pretty sure this will be a piece of cake for y`all, but I'm trying to add pagination to my loop. I've tried some codes that were available around, and got to paginate it, but pages 2, 3, etc had the same content from page 1. What's the best solution for what I have at the moment?
```
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<article>
</article>
<?php endwhile; ?>
```
Thanks in advance.
|
Likely this is happening because you are using a custom page template. Try the following. I've commented the steps along the way. Hope it helps.
```
<?php
//get the current page
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
//pagination fixes prior to loop
$temp = $query;
$query = null;
//custom loop using WP_Query
$query = new WP_Query( array(
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'ASC'
) );
//set our query's pagination to $paged
$query -> query('post_type=post&posts_per_page=5'.'&paged='.$paged);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
?>
<li>
<?php if ( has_post_thumbnail()) : ?>
<?php the_post_thumbnail();?>
<?php endif; ?>
<div class="someclass" >
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</li>
<?php endwhile;?>
<?php //pass in the max_num_pages, which is total pages ?>
<div class="pagenav">
<div class="alignleft"><?php previous_posts_link('Previous', $query->max_num_pages) ?></div>
<div class="alignright"><?php next_posts_link('Next', $query->max_num_pages) ?></div>
</div>
<?php endif; ?>
<?php //reset the following that was set above prior to loop
$query = null; $query = $temp; ?>
```
|
203,787 |
<p>I am trying to add the current post's author as the content for the meta author tag. I wrapped this particular meta in an <code>is_single</code> condition and then tried:</p>
<pre><code><meta name="author" content="<?php get_the_author(); ?>" />
</code></pre>
<p>as well as tried this:</p>
<pre><code><meta name="author" content="<?php the_author(); ?>" />
</code></pre>
<p>For both the above, <a href="https://developers.facebook.com/tools/debug/" rel="nofollow noreferrer">Facebook debugger</a> responded with:</p>
<p><strong>Meta with name instead of property</strong> : The meta tag on the page was specified with name 'author', which matches a configured property of this object type. It will be ignored unless specified with the meta property attribute instead of the meta name attribute.</p>
<hr />
<p>Then I tried:</p>
<pre><code><meta property="article:author" content="<?php the_author(); ?>" />
</code></pre>
<p>as well as tried this:</p>
<pre><code><meta property="article:author" content="<?php get_the_author(); ?>" />
</code></pre>
<p>For both the above, <a href="https://developers.facebook.com/tools/debug/" rel="nofollow noreferrer">Facebook debugger</a> responded with:</p>
<p><strong>Parser Mismatched Metadata</strong> : The parser's result for this metadata did not match the input metadata. Likely, this was caused by the data being ordered in an unexpected way, multiple values being given for a property only expecting a single value, or property values for a given property being mismatched. Here are the input properties that were not seen in the parsed result: 'article:author'.</p>
<hr />
<p>What am I doing wrong as all of the above four metas just return a blank content (<code><meta name="author" content/></code>) for the <code>author</code> tag.</p>
|
[
{
"answer_id": 203826,
"author": "coopersita",
"author_id": 21258,
"author_profile": "https://wordpress.stackexchange.com/users/21258",
"pm_score": 2,
"selected": false,
"text": "<p>You cad add it via <code>functions.php</code> with a hook, instead of inside the loop (you don't really want to add a loop to header.php):</p>\n\n<pre><code>function add_author_meta() {\n\n if (is_single()){\n global $post;\n $author = get_the_author_meta('user_nicename', $post->post_author);\n echo \"<meta name=\\\"author\\\" content=\\\"$author\\\">\";\n }\n}\nadd_action( 'wp_enqueue_scripts', 'add_author_meta' );\n</code></pre>\n"
},
{
"answer_id": 220507,
"author": "Harkály Gergő",
"author_id": 71655,
"author_profile": "https://wordpress.stackexchange.com/users/71655",
"pm_score": 0,
"selected": false,
"text": "<p>Add this into header.php</p>\n\n<pre><code><meta name=\"author\" content=\"<?php the_author_meta('user_nicename', $post->post_author); ?>\">\n</code></pre>\n"
},
{
"answer_id": 355595,
"author": "Rajnish Suvagiya",
"author_id": 128293,
"author_profile": "https://wordpress.stackexchange.com/users/128293",
"pm_score": 0,
"selected": false,
"text": "<p>You can add meta tags using <code>wp_head</code> hook action from <code>functions.php</code> of the Themes files or create a custom plugin.</p>\n\n<p>Here you can check example.</p>\n\n<pre><code>add_action('wp_head', 'fc_opengraph');\n\nfunction fc_opengraph() {\n\n\n if ( is_single() || is_page() ) {\n\n $post_id = get_queried_object_id(); // get current post id\n\n $author_name = 'set your author name';\n\n $site_name = get_bloginfo('name');\n\n $description = wp_trim_words( get_post_field('post_content', $post_id), 25 );\n\n $image = get_the_post_thumbnail_url($post_id);\n\n if( !empty( get_post_meta($post_id, 'og_image', true) ) ) $image = get_post_meta($post_id, 'og_image', true);\n\n $locale = get_locale();\n\n echo '<meta property=\"og:locale\" content=\"' . esc_attr($locale) . '\" />';\n echo '<meta property=\"og:type\" content=\"article\" />';\n echo '<meta property=\"author\" content=\"' . esc_attr($author_name) . '\" />';\n echo '<meta property=\"og:description\" content=\"' . esc_attr($description) . '\" />';\n echo '<meta property=\"og:url\" content=\"' . esc_url($url) . '\" />';\n echo '<meta property=\"og:site_name\" content=\"' . esc_attr($site_name) . '\" />';\n\n if($image) echo '<meta property=\"og:image\" content=\"' . esc_url($image) . '\" />';\n\n }\n\n}\n</code></pre>\n\n<p>Please check this url for the hook documentation: <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/wp_head/</a></p>\n"
}
] |
2015/09/26
|
[
"https://wordpress.stackexchange.com/questions/203787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74607/"
] |
I am trying to add the current post's author as the content for the meta author tag. I wrapped this particular meta in an `is_single` condition and then tried:
```
<meta name="author" content="<?php get_the_author(); ?>" />
```
as well as tried this:
```
<meta name="author" content="<?php the_author(); ?>" />
```
For both the above, [Facebook debugger](https://developers.facebook.com/tools/debug/) responded with:
**Meta with name instead of property** : The meta tag on the page was specified with name 'author', which matches a configured property of this object type. It will be ignored unless specified with the meta property attribute instead of the meta name attribute.
---
Then I tried:
```
<meta property="article:author" content="<?php the_author(); ?>" />
```
as well as tried this:
```
<meta property="article:author" content="<?php get_the_author(); ?>" />
```
For both the above, [Facebook debugger](https://developers.facebook.com/tools/debug/) responded with:
**Parser Mismatched Metadata** : The parser's result for this metadata did not match the input metadata. Likely, this was caused by the data being ordered in an unexpected way, multiple values being given for a property only expecting a single value, or property values for a given property being mismatched. Here are the input properties that were not seen in the parsed result: 'article:author'.
---
What am I doing wrong as all of the above four metas just return a blank content (`<meta name="author" content/>`) for the `author` tag.
|
You cad add it via `functions.php` with a hook, instead of inside the loop (you don't really want to add a loop to header.php):
```
function add_author_meta() {
if (is_single()){
global $post;
$author = get_the_author_meta('user_nicename', $post->post_author);
echo "<meta name=\"author\" content=\"$author\">";
}
}
add_action( 'wp_enqueue_scripts', 'add_author_meta' );
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.